C语言 获取一个字符的子串*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4214314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:06:19  来源:igfitidea点击:

Get a substring of a char*

ccharsubstring

提问by Goz

For example, I have this

例如,我有这个

char *buff = "this is a test string";

and want to get "test". How can I do that?

并且想要得到"test"。我怎样才能做到这一点?

回答by Goz

char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
';

Job done :)

任务完成 :)

回答by Blagovest Buyukliev

Assuming you know the position and the length of the substring:

假设您知道子串的位置和长度:

char* substr = malloc(4);
strncpy(substr, buff+10, 4);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

您可以通过将子字符串复制到另一个内存目标来实现相同的目的,但这是不合理的,因为您已经在内存中拥有它。

This is a good example of avoiding unnecessary copying by using pointers.

这是使用指针避免不必要复制的一个很好的例子。

回答by Mihai Scurtu

Use char* strncpy(char* dest, char* src, int n)from <cstring>. In your case you will need to use the following code:

char* strncpy(char* dest, char* src, int n)从使用<cstring>。在您的情况下,您将需要使用以下代码:

##代码##

Full documentation on the strncpyfunction here.

此处提供有关该strncpy功能的完整文档。

回答by Milan

You can use strstr. Example code here.

您可以使用strstr. 示例代码在这里

Note that the returned result is not null terminated.

请注意,返回的结果不是空终止的。

回答by Paul R

You can just use strstr()from <string.h>

你可以使用strstr()from<string.h>

$ man strstr

$ man strstr