[英]I'm trying to split a string by a delimiter but it doesn't work, why?
I wrote below code to readin line by line from stdin ex. 我写了下面的代码从stdin ex逐行读入。
city=Boston;city=New York;city=Chicago\n
and then split each line by ';' 然后用“;”分隔每一行 delimiter and print each record. 定界符并打印每个记录。
But for some reason the "record" pointer comes back always null. 但是由于某种原因,“记录”指针总是返回空值。 Why? 为什么?
char del = ';';
char input[BUFLEN];
while(fgets(input, BUFLEN, fp)) {
input[strlen(input)-1]='\0';
char* record = strtok(input, &del);
while(record) {
printf("Record: %s\n",record);
record = strtok(NULL, &del);
}
}
strtok
needs a string with a nul (zero byte) at the end for its second argument. strtok
的第二个参数需要一个结尾为nul(零字节)的字符串。 Change del
to be 将del
更改为
char * del = ";"
Here is a full program (minus the input reading part): 这是完整的程序(减去输入阅读部分):
#include <string.h>
#include <stdio.h>
int main ()
{
char* del = ";";
char * input = strdup ("city=Boston;city=New York;city=Chicago\n");
char* record = strtok (input, del);
while (record) {
printf("Record: %s\n",record);
record = strtok (NULL, del);
}
}
Try it: http://codepad.org/tzzxjOJE 试试看: http : //codepad.org/tzzxjOJE
There is also a strsep
function which has the advantage of handling more than one string at a time. 还有一个strsep
函数 ,它的优点是一次处理多个字符串。
Try char * del = ";"; 尝试char * del =“;”;
The second parameter should be a null terminated string, ie an array of chars with a null termination. 第二个参数应该是一个以null结尾的字符串,即一个以null结尾的char数组。
And then pass in del to strtok. 然后将del传递给strtok。
char* del = ";";
char input[BUFLEN];
while(fgets(input, BUFLEN, fp)) {
input[strlen(input)-1]='\0';
char* record = strtok(input, del);
while(record) {
printf("Record: %s\n",record);
record = strtok(NULL, del);
}
}
Your call to strtok() is very likely to segfault. 您对strtok()的调用很可能会发生段错误。 The char * pointed to by &del does not have a NULL terminator. &del指向的char *没有NULL终止符。
strtok()
expects the delimiters string to be exactly that - a null-terminated C string. strtok()
希望定界符字符串恰好是-以空值终止的C字符串。 You're passing it a single character, which obviously isn't a null-terminated string since a semicolon is not a null character. 您正在为它传递一个字符,因为分号不是空字符,所以它显然不是以空字符结尾的字符串。 Instead, try this: 相反,请尝试以下操作:
char del[] = ";";
I'm not sure but I think because your del won't have the proper '\\0' at the end. 我不确定,但我认为是因为您的del末尾没有正确的'\\ 0'。
You have to make sure the string is NULL terminated or most of the string function are gonna read the memory after your variable which could leads to LOTS of problems 您必须确保字符串以NULL终止,否则大多数字符串函数将在变量之后读取内存,这可能会导致很多问题
something like this would be better: 这样的事情会更好:
char *del = ";";
char input[BUFLEN];
while(fgets(input, BUFLEN, fp)) {
input[strlen(input)-1]='\0';
char* record = strtok(input, del);
while(record) {
printf("Record: %s\n",record);
record = strtok(NULL, del);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.