c - 如何从 C 中的字符串中获取子字符串?

标签 c string pointers

我想在 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/

相关文章:

在 C 编译期间更改函数体

c - C中分数简化程序的浮点异常

C - 套接字编程客户端服务器 - 主机名连接

java - java中char数组到String数组的转换

c - 字符串操作和 rot-13

c++ - 生成特定长度的 powerset

c - 没有这样的过程 - ptrace

c++ - 遍历指针 vector

c++ - 带指针的 std::map:错误的值评估

c++ - size_t ptrdiff_t 和地址空间