我的字符串是 "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
谢谢。
您可以更改分隔符集,因此只需传递一个空字符串:
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);
不要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);
}
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);
}
注意:这不是线程安全的。
尝试这个:
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);
}
}
如果 usingstrtok
不是必需的,则可以使用strchr
,因为分隔符是单个字符:
char a[] = "A,B,C,D,E";
char *sep = strchr(a, ',');
*sep = '\0';
puts(a);
puts(sep + 1);
printf("a: %s\n", a+1+strlen(b));
尝试这个
有更好的方法来处理 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;
}