43

我想知道如何获取 1 个字符串,用分隔符(例如空格)将其分成 2 个,然后将 2 个部分分配给 2 个单独的字符串。我试过使用strtok()但无济于事。

4

8 回答 8

60
#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);

更新

请注意,在某些操作系统上,strtok手册页提到:

此接口已被 strsep(3) 废弃。

一个例子strsep如下所示:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}
于 2010-03-26T13:22:19.973 回答
13

出于这样的目的,我倾向于使用 strtok_r() 而不是 strtok()。

例如 ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

这将输出...

'123456' '789asdf'

如果需要更多分隔符,则循环。

希望这可以帮助。

于 2010-03-26T13:25:12.057 回答
4
char *line = strdup("user name"); // don't do char *line = "user name"; see Note

char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " ");   //sec_part points to "name"

注意:strtok修改字符串,所以不要给它一个指向字符串文字的指针。

于 2010-03-26T13:23:06.863 回答
3

您可以将 strtok() 用于该示例:它适用于我

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

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }
    return 0;
}
于 2010-03-26T13:23:10.513 回答
2

如果您分配了一个 char 数组,您可以简单地将 a 放在'\0'您想要的任何地方。然后将一个新的 char* 指针指向新插入后的位置'\0'

这将破坏您的原始字符串,但这取决于您将'\0'

于 2010-03-26T13:22:00.953 回答
1

如果您愿意更改原始字符串,只需将分隔符替换为\0. 原始指针将指向第一个字符串,而指向分隔符之后的字符的指针将指向第二个字符串。好消息是您可以同时使用两个指针,而无需分配任何新的字符串缓冲区。

于 2010-03-26T13:21:47.493 回答
1

你可以做:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

如果您期望多个令牌,最好strtok在 while 循环中调用第二个和后续调用,直到返回值strtokbecome NULL

于 2010-03-26T13:27:40.303 回答
1

这就是您实现strtok()类似函数的方式(取自BSD 许可的 C 字符串处理库,称为 zString)。

下面的函数strtok()在识别连续分隔符的方式上与标准不同,而标准strtok()则不然。

char *zstring_strtok(char *str, const char *delim) {
    static char *static_str=0;      /* var to store last address */
    int index=0, strlength=0;       /* integers for indexes */
    int found = 0;                  /* check if delim is found */

    /* delimiter cannot be NULL
    * if no more char left, return NULL as well
    */
    if (delim==0 || (str == 0 && static_str == 0))
        return 0;

    if (str == 0)
        str = static_str;

    /* get length of string */
    while(str[strlength])
        strlength++;

    /* find the first occurance of delim */
    for (index=0;index<strlength;index++)
        if (str[index]==delim[0]) {
            found=1;
            break;
        }

    /* if delim is not contained in str, return str */
    if (!found) {
        static_str = 0;
        return str;
    }

    /* check for consecutive delimiters
    *if first char is delim, return delim
    */
    if (str[0]==delim[0]) {
        static_str = (str + 1);
        return (char *)delim;
    }

    /* terminate the string
    * this assignmetn requires char[], so str has to
    * be char[] rather than *char
    */
    str[index] = '\0';

    /* save the rest of the string */
    if ((str + index + 1)!=0)
        static_str = (str + index + 1);
    else
        static_str = 0;

        return str;
}

下面是一个演示用法的示例代码

  Example Usage
      char str[] = "A,B,,,C";
      printf("1 %s\n",zstring_strtok(s,","));
      printf("2 %s\n",zstring_strtok(NULL,","));
      printf("3 %s\n",zstring_strtok(NULL,","));
      printf("4 %s\n",zstring_strtok(NULL,","));
      printf("5 %s\n",zstring_strtok(NULL,","));
      printf("6 %s\n",zstring_strtok(NULL,","));

  Example Output
      1 A
      2 B
      3 ,
      4 ,
      5 C
      6 (null)

您甚至可以使用 while 循环(标准库strtok()会在这里给出相同的结果)

char s[]="some text here;
do {
    printf("%s\n",zstring_strtok(s," "));
} while(zstring_strtok(NULL," "));
于 2016-02-18T23:43:16.620 回答