1

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 ?

utsabiem
  • 920
  • 4
  • 10
  • 21

6 Answers6

1

try to look for strtok()

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
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++?

Community
  • 1
  • 1
bobbymcr
  • 23,769
  • 3
  • 56
  • 67
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
0

You can use strtok to split the string in C.

Naveen
  • 74,600
  • 47
  • 176
  • 233
0

For substring use strndup. For tokenizing/splitting use strtok.

Igor
  • 26,650
  • 27
  • 89
  • 114