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
Get a substring of a char*
提问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.
这是使用指针避免不必要复制的一个很好的例子。

