例如,我有这样一个例子
char *buff = "this is a test string";
想要得到"test"
。我该怎么做呢?
发布于 2010-11-18 19:41:10
char subbuff[5];
memcpy( subbuff, &buff[10], 4 );
subbuff[4] = '\0';
工作完成:)
发布于 2010-11-18 19:40:49
假设您知道该子字符串的位置和长度:
char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);
您可以通过将子字符串复制到另一个内存目标来实现相同的功能,但这是不合理的,因为您已经在内存中拥有它。
这是通过使用指针避免不必要的复制的一个很好的例子。
发布于 2010-11-18 19:47:02
使用<cstring>
中的char* strncpy(char* dest, char* src, int n)
。在您的示例中,您需要使用以下代码:
char* substr = malloc(4);
strncpy(substr, buff+10, 4);
有关strncpy
函数here的完整文档。
https://stackoverflow.com/questions/4214314
复制相似问题