简体   繁体   English

从C中的字符串中获取子字符串

[英]Take substring from a string in C

I have a string 'Merry Christmas'. 我有一个字母'圣诞快乐'。 I want to separate this one as 'Merry' and 'Christmas'. 我想把这个分开为'Merry'和'Christmas'。 In Objective c, I could do it easily by componentsSeparatedByString: . 在Objective c中,我可以通过componentsSeparatedByString:轻松完成componentsSeparatedByString: How to do this in C ? 如何在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). 纯C的标准方法是使用strtok ,虽然它是一个相当危险和破坏性的函数(它修改了传入的字符缓冲区)。

In C++ , there are better ways; C ++中 ,有更好的方法; see here: How do I tokenize a string in C++? 请参阅此处: 如何在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 ). C库包括strtok(), strspn() and strcspn() ,你所谓的String是一个char数组(以\\0结尾)。

strtok is the generic solution for string tokenizing. strtok是字符串标记化的通用解决方案。 A simpler, more limited way is to use strchr: 更简单,更有限的方法是使用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 . 对于子串使用strndup For tokenizing/splitting use strtok . 对于标记化/拆分使用strtok

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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