例如,我有以下这个:
char *buff = "this is a test string";
我想获取"test"
。我该怎么做?
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
工作完成 :)
假设您知道子字符串的位置和长度:
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
你可以通过将子字符串复制到另一个内存目标来实现相同的效果,但这并不合理,因为你已经在内存中拥有它。
这是使用指针避免不必要复制的好例子。
%c
、%i
等占位符,那么从第三个参数到占位符数量为止,就是占位符的实际值(用逗号分隔)。就像 printf
一样。 - Parnab Sanyal使用来自<cstring>的char* strncpy(char* dest, char* src, int n)
。在你的情况下,你需要使用以下代码:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
此处提供了关于strncpy
函数的完整文档。
char *substr(char const *s, size_t start, size_t length)
{
char *substr = calloc(length + 1, sizeof(char));
strncpy(substr, s + start, length);
return substr;
}
- VDVLeonstrstr()
返回它找到的子字符串的第一个索引,但你说它不仅仅是子字符串。 - VimNing