How do you split a string in two halves using C? I've looked everywhere for the answer but most seem to deal with splitting at spaces or other characters (examples 1, 2, 3). I just want to split a string into 2 halves. Is there a simple way to do this?
2 Answers
No, there's no simple way of doing it - it takes several steps:
- Compute the length of the string
- Allocate memory for both halves
- Copy the content into the first half; add null termination
- Copy the content into the second half; add a null terminator
- Use your strings
- Free the first copy
- Free the second copy
Here is how you can do it:
char *str = "quickbrownfox";
int len = strlen(str);
int len1 = len/2;
int len2 = len - len1; // Compensate for possible odd length
char *s1 = malloc(len1+1); // one for the null terminator
memcpy(s1, str, len1);
s1[len1] = '\0';
char *s2 = malloc(len2+1); // one for the null terminator
memcpy(s2, str+len1, len2);
s2[len2] = '\0';
...
free(s1);
free(s2);
If you own the entire string, you do not need to make a second copy, because making a pointer into the middle of a string will just work.
5 Comments
Sergey Kalinichenko
Here is a demo on ideone.
Sergey Kalinichenko
@H2CO3 C'mon, spending so many lines of code on a simple pair of
substrs is not simple - it's almost like we're back to assembly language programming.Some say that C is almost like assembly. While I don't agree, I do get the point. My opinion, though, is that this is not what counts as difficult. Creating a complete operating system, writing a 3D engine with heavy maths, coding AI... That's what I call difficult. (I don't say that "German language is hard" just because I don't speak German. Surely I could learn it if I wanted. It's all about effort and practice.)
Jack Johnson
yea i figured there wouldn't be an easy way like in java or some other language. thanks this helped
"abcde"is to be"abc"and"de"or"ab"and"cde"? (ignoring\n).&string[n/2]is the second half.