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?
Asked
Active
Viewed 1.1k times
1
-
1Sure. Learned math in high school, right? – Oct 10 '13 at 20:52
-
Why can't you find split point using strlen()? – zubergu Oct 10 '13 at 20:52
-
1Two halves? `"abcde"` is to be `"abc"` and `"de"` or `"ab"` and `"cde"`? (ignoring `\n`). – haccks Oct 10 '13 at 20:53
-
If you know how long the string is (say, _n_), then a copy of the substring from indices [0,n/2) is the first half, and `&string[n/2]` is the second half. – Joshua Taylor Oct 10 '13 at 20:53
-
` void split(char *s, char **a, char **b) { int i = strlen(s) / 2; char c = s[i]; s[i] = 0; *a = strdup(s); s[i] = c; *b = strdup(s + i); }` – Charlie Burns Oct 10 '13 at 20:57
2 Answers
3
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.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
-
"there's no simple way of doing it" - Um, I'm sure this is considered pretty simple. I'd say trivial. – Oct 10 '13 at 21:18
-
@H2CO3 C'mon, spending so many lines of code on a simple pair of `substr`s is not simple - it's almost like we're back to assembly language programming. – Sergey Kalinichenko Oct 10 '13 at 21:22
-
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.) – Oct 10 '13 at 21:25
-
yea i figured there wouldn't be an easy way like in java or some other language. thanks this helped – Jack Johnson Oct 10 '13 at 22:00
1
Not if you want to do it in-place. You'd have to sacrifice one character for the '\0'
byte.
You'll need to think about how you want to allocate memory for the 2nd part of the split string, and code accordingly.

mpontillo
- 13,559
- 7
- 62
- 90