C语言:如何在使用strtok()一次后获取剩余的字符串

时间:2013-11-01 09:58:01

标签: c strtok

我的字符串是" A,B,C,D,E"
分隔符是","
如何在执行strtok()之后获取剩余的字符串,即" B,C,D,E"

char a[] = "A,B,C,D,E";
char * separator = ",";
char * b = strtok(a,separator);
printf("a: %s\n", a);
printf("b: %s\n", b);

输出结果为:
a:A
b:A

但如何得到结果
a:B,C,D,E
b:A

感谢。

7 个答案:

答案 0 :(得分:17)

您可以改变分隔符集,因此只需传递一个空字符串:

char a[] = "A,B,C,D,E";
char * separator = ",";
char * b = strtok(a, separator);
printf("b: %s\n", b);
char * c = strtok(NULL, "");
printf("c: %s\n", c);

答案 1 :(得分:8)

不要使用strtok(),因为那不是它的用途。

使用strchr()查找第一个分隔符,然后从那里开始:

char a[] = "A,B,C,D,E";
const char separator = ',';
char * const sep_at = strchr(a, separator);
if(sep_at != NULL)
{
  *sep_at = '\0'; /* overwrite first separator, creating two strings. */
  printf("first part: '%s'\nsecond part: '%s'\n", a, sep_at + 1);
}

答案 2 :(得分:1)

试试这个:

char a[] = "A,B,C,D,E";
char * end_of_a = a + strlen(a); /* Memorise the end of s. */
char * separator = ",";
char * b = strtok(a, separator);
printf("a: %s\n", a);
printf("b: %s\n", b);

/* There might be some more tokenising here, assigning its result to b. */

if (NULL != b)
{
  b = strtok(NULL, separator);
}

if (NULL != b)
{ /* Get reference to and print remainder: */
  char * end_of_b = b + strlen(b);

  if (end_of_b != end_of_a) /* Test whether there really needs to be something, 
                        will say tokenising did not already reached the end of a, 
                        which however is not the case for this example.  */
  {
    char * remainder = end_of_b + 1;
    printf("remainder: `%s`\n", remainder);
  }   
}

答案 3 :(得分:1)

strtok会记住它使用的最后一个字符串以及它的结束位置。要获取下一个字符串,请以NULL作为第一个参数再次调用它。

char a[] = "A,B,C,D,E";
const char *separator = ",";
char *b = strtok(a, separator);
while (b) {
    printf("element: %s\n", b);
    b = strtok(NULL, separator);
}

注意:这不是线程安全的。

答案 4 :(得分:0)

如果不要求使用strtok,则可以使用strchr,因为分隔符是单个字符:

char a[] = "A,B,C,D,E";
char *sep = strchr(a, ',');
*sep = '\0';
puts(a);
puts(sep + 1);

答案 5 :(得分:0)

  

printf(“a:%s \ n”,a + 1 + strlen(b));

试试这个

答案 6 :(得分:0)

有更好的方法来处理 IP 地址,但这是一个实际示例,需要在执行过程中的某个点从 '.' 更改为 '/'

struct Ip split_ip_by_octet(char ip_string[]) {

    struct Ip ip;
    char * value_before_delimeter = strtok(ip_string, "."); // N. 

    if (value_before_delimeter != NULL) {
        sscanf(value_before_delimeter, "%d", &ip.octet_1);
        value_before_delimeter = strtok(NULL, ".");        // n.N.

        sscanf(value_before_delimeter, "%d", &ip.octet_2);
        value_before_delimeter = strtok(NULL, ".");        // n.n.N.n/n

        sscanf(value_before_delimeter, "%d", &ip.octet_3);
        value_before_delimeter = strtok(NULL, "/");        // n.n.n.N/n

        sscanf(value_before_delimeter, "%d", &ip.octet_4);
        value_before_delimeter = strtok(NULL, "");         // n.n.n.n/N

        sscanf(value_before_delimeter, "%d", &ip.mask);
    }
    return ip; 
}