开发者

How do I split a string once?

I want to split a string into only two parts at the first space character. For exampl开发者_如何学Ce, I have a string "Hay Guys LOL" and when split, "Hay" should be in one variable, and "Guys LOL" in the other.

I have looked into functions like strtok - it works, but I would prefer not looping and then combining the strings.

Here is what I currently have (trying sscanf):

char test[32];
strcpy(test, "Hay Guys LOL\r\n");

// p1 should have "Hay", and p2 have "Guys LOL"?
char p1[16], p2[16];
sscanf(test, "%s %s\r\n", p1, p2);

printf("p1: %s\n", p1);
printf("p2: %s\n", p2);

Thanks!


Make it:

sscanf(test, "%s %[^\r\n]", p1, p2);

The first %s will only read the first string upto the first blankspace read "Hay". Next the scanset will read until a '\r' or '\n' is not found in the string (^ in the [] inverts the set) . Therefore the %[^\r\n] will read the rest of the string into p2.

UPDATE

As @Adam Rosenfield told, to avoid buffer overflows you need to limit the numbers of characters put into p1 and p2 by sscanf. You specify the nos of characters like %10[^\r\n] and %10s . Because these numbers needs to be a part of the format string therefore you might want to make the format string dynamically before use.

char format_string[MAX];

sprintf (format_string, "%%%ds %%%d[^\\r\\n]", 10, 10);

sscanf (test, format_string, p1, p2);

Above the format string with the length limitation is made first and then it is used. Note the escape characters. %% is used to print a single % in the output and \\ is used to print a single \ in the output string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜