我想在 C 中创建一个从字符串中获取子字符串的函数。这是我目前所拥有的:
char* substr(char* src, int start, int len){
char* sub = malloc(sizeof(char)*(len+1));
memcpy(sub, &src[start], len);
sub[len] = '\0';
return sub;
}
int main(){
char* test = malloc(sizeof(char)*5); // the reason I don't use char* = "test"; is because I wouldn't be able to use free() on it then
strcpy(test, "test");
char* sub = substr(test, 1, 2); // save the substr in a new char*
free(test); // just wanted the substr from test
printf("%s\n", sub); // prints "es"
// ... free when done with sub
free(sub);
}
有什么方法可以将子字符串保存到 test
而无需创建新的 char*
?如果我执行 test = substr(test, 1, 2)
,test
的旧值不再有指向它的指针,所以它是内存泄漏(我认为。说到 C 语言,我是菜鸟。)
最佳答案
void substr(char* str, char* sub , int start, int len){
memcpy(sub, &str[start], len);
sub[len] = '\0';
}
int main(void)
{
char *test = (char*)malloc(sizeof(char)*5);
char *sub = (char*)malloc(sizeof(char)*3);
strcpy(test, "test");
substr(test, sub, 1, 2);
printf("%s\n", sub); // prints "es"
free(test);
free(sub);
return 0;
}
关于c - 如何从 C 中的字符串中获取子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29439150/