I need to split a string into string based on the location of a character. So that:
str1 = “hello?world” is str1 = “hello” and str2 = “world”
This is what I have so far:
char str1[100] = "hello?world";
char str2[100];
char *p;
p = strpbrk(str1, "?");
strcpy(&str2, p);
strcspn(str1, '?');
I get errors when trying to copy the characters after ‘p’ to str2. There has got to be a better and functional way. Can someone help me out? Many thanks…
This
is an error,
strcspn‘s second parameter is aconst char*, passing a character constant there is almost certain to cause undefined behaviour and a segmentation fault (Your programme is very unlikely to have the address 63 (ASCII value of ‘?’) in its address space, and if it has, it’s unlikely to point to a 0-terminated character array).ought to work. If you want to end
str1at the ‘?’,*p = 0;overwrites the ‘?’ with a 0. But of course generally, you should verify thatstrpbrkdoesn’t returnNULLbefore usingp.