I want to split a string into only two parts at the first space character. For example, 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:
The first
%swill 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 intop2.UPDATE
As @Adam Rosenfield told, to avoid buffer overflows you need to limit the numbers of characters put into
p1andp2bysscanf. 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.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.