【发布时间】:2011-05-11 23:43:29
【问题描述】:
例如,我有这个
char *buff = "this is a test string";
并想获得"test"。我该怎么做?
【问题讨论】:
例如,我有这个
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
使用来自<cstring> 的char* strncpy(char* dest, char* src, int n)。在您的情况下,您将需要使用以下代码:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
关于strncpy 函数here 的完整文档。
【讨论】:
您可以使用strstr。示例代码here。
注意返回的结果不是以null结尾的。
【讨论】:
您可以只使用来自<string.h> 的strstr()
【讨论】:
def 是 abcdefghi 的子字符串
strstr()返回它找到的子串的第一个索引,但你说它不仅仅是子串。
this is a test string 获取test。这个答案将返回test string,而不仅仅是test。