I have a string 'Merry Christmas'. I want to separate this one as 'Merry' and 'Christmas'. In Objective c, I could do it easily by componentsSeparatedByString:
. How to do this in C ?
Asked
Active
Viewed 1,682 times
1

utsabiem
- 920
- 4
- 10
- 21
6 Answers
1
The standard way in pure C is to use strtok
, although it's a rather dangerous and destructive function (it modifies the passed in character buffer).
In C++, there are better ways; see here: How do I tokenize a string in C++?
1
You have to write your own function.
The C library include strtok(), strspn() and strcspn()
and what you call a String is an array of char (which end by \0
).

COD3BOY
- 11,964
- 1
- 38
- 56

JohnJohnGa
- 15,446
- 19
- 62
- 87
1
strtok is the generic solution for string tokenizing. A simpler, more limited way is to use strchr:
#include <string.h> // strchr, strcpy
#include <stddef.h> // NULL
const char str[] = "Merry Christmas";
const char* ptr_merry = str;
const char* ptr_christmas;
ptr_christmas = strchr(str, ' ');
if(ptr_christmas != NULL)
{
ptr_christmas++; // point to the first character after the space
}
// optionally, make hard copies of the strings, if you want to alter them:
char hardcpy_merry[N];
char hardcpy_christmas[n];
strcpy(hardcpy_merry, ptr_merry);
strcpy(hardcpy_christmas, ptr_christmas);

Lundin
- 195,001
- 40
- 254
- 396