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 ?

6 Answers 6

1

try to look for strtok()

Sign up to request clarification or add additional context in comments.

Comments

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++?

Comments

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).

Comments

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);

Comments

0

You can use strtok to split the string in C.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.