如何在任意索引处拆分字符串?

use*_*767 0 c string split

如何将字符串分成几段?例如,我如何放置“orld”。放入名为 的变量中one,将“Hello”放入名为 的变量中three,并将“w”放入two?

#include <string.h>
#include <stdio.h>

int main(void)
{
    char *text ="Hello World."; /*12 C*/

    char one[5];
    char two[5];
    char three[2];

    return 1;
}
Run Code Online (Sandbox Code Playgroud)

Mer*_*ham 5

其一,您无法执行您所要求的操作,并且仍然让它们作为空终止字符串工作。这是因为 的内存布局text如下所示:

char text_as_array[] = {
  'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '.', '\0'
};
Run Code Online (Sandbox Code Playgroud)

注意'\0'最后的。字符数组的test长度实际上不是 12 ,而是长度13

控制台输出函数(例如 printf 和 std::cout (C++))需要空终止才能工作:

char good[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
printf("%s\n", good); /* this works, because it is null-terminated */

char bad[] = { 'H', 'e', 'l', 'l', };
printf("%s\n", bad); /* this will print out garbage, or crash your program! */
Run Code Online (Sandbox Code Playgroud)

这意味着您必须像这样定义数组:

char one[6];
char two[3];
char three[6];
Run Code Online (Sandbox Code Playgroud)

您可以通过简单地将值复制出来来手动完成此操作:

one[0] = text[7]; /* o */
one[1] = text[8]; /* r */
one[2] = text[9]; /* l */
one[3] = text[10]; /* d */
one[4] = text[11]; /* . */
one[5] = '\0'; /* you have to null-terminate the string */
Run Code Online (Sandbox Code Playgroud)

如果您想减少输入次数,或者只是想编写更好的代码,您可以利用数组/字符串是连续的这一事实,并使用循环来复制该数据:

for(int i = 0; i < 5; ++i)
{
  one[i] = text[7 + i];
}
one[5] = '\0';
Run Code Online (Sandbox Code Playgroud)

但如果您猜想这在 C 语言中确实很常见,那么您猜对了。您应该使用内置函数来为您进行复制,而不是每次都手动编码此循环:

/* C uses "", C++ uses <> */
#include "string.h" /* C++: #include<cstring> */
#include "stdio.h" /* C++: #include<cstdio> */

/* don't do "int function(void)", do "int function()" instead */
int main()
{
  char *text = "Hello World."; /* string length 12, array size 13 */

  /* size of these has to accomodate the terminating null */
  char one[6];
  char two[3];
  char three[6];

  /* copy two characters, starting at index 5 */
  strncpy(two, &text[5], 2);

  /* for three, we don't have to do &text[0], because it is at the beginning of the string */
  strncpy(three, text, 5);

  /* we can do strcpy if we're at the end of the string.  It will stop when it hits '\0' */
  strcpy(one, &text[7]);

  /* note that we still have to null-terminate the strings when we use strncpy */
  two[2] = '\0';
  three[5] = '\0';

  /* but we don't have to null-terminate when we use strcpy */
  /* so we can comment this out: one[5] = '\0'; */

  printf("%s\n", one);
  printf("%s\n", two);
  printf("%s\n", three);

  return 0; /* returns 0, since no errors occurred */
}
Run Code Online (Sandbox Code Playgroud)