简体   繁体   中英

Take substring from a string in C

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 ?

试着寻找strtok()

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

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

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

您可以使用strtok在C中拆分字符串。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM