You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何存储C++字符串去重函数的返回值并进行操作?

如何存储removeDuplicate函数的返回值并进行后续操作?

首先得给你的函数补个关键小漏洞:它没有在去重后的字符串末尾添加字符串结束符'\0',这会导致后续用printf、strlen这类字符串函数时读到内存里的垃圾数据。先修改下函数:

char *removeDuplicate(char str[], int n) {
    int index = 0;
    for (int i=0; i<n; i++) {
        int j;
        for (j=0; j<i; j++)
            if (str[i] == str[j])
                break;
        if (j == i)
            str[index++] = str[i];
    }
    // 必须加上这行,让字符串正确终止
    str[index] = '\0';
    return str;
}

接下来讲怎么存储返回值和后续操作:

这个函数的核心特点是原地修改输入的字符数组——它直接把去重后的字符放到原数组的开头,返回的指针其实就是你传入的原数组的地址。所以存储和使用的方式很灵活:

1. 直接接收返回值并操作(原地修改场景)

如果不需要保留原字符串,直接用栈上的数组或者已有的字符数组传入函数,然后用char*变量接收返回值,或者直接用原数组名操作:

#include <stdio.h>
#include <string.h>

// 上面修改后的removeDuplicate函数

int main() {
    // 定义输入字符串(栈上数组,生命周期在main函数内)
    char myStr[] = "aabbbccddeeffgg";
    int strLen = strlen(myStr);
    
    // 用char*变量接收返回值,其实就是myStr的地址
    char *deduplicated = removeDuplicate(myStr, strLen);
    
    // 后续操作示例:
    // 1. 打印结果
    printf("去重后:%s\n", deduplicated);
    // 2. 获取去重后的长度
    printf("长度:%zu\n", strlen(deduplicated));
    // 3. 遍历每个字符
    for (int i = 0; deduplicated[i] != '\0'; i++) {
        printf("字符%d:%c\n", i+1, deduplicated[i]);
    }
    
    return 0;
}

2. 保留原字符串的场景

如果不想破坏原字符串,需要先复制一份原字符串,再把副本传入函数:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// 上面修改后的removeDuplicate函数

int main() {
    const char *original = "hello world hello";
    // 用strdup复制原字符串到动态分配的内存
    char *copy = strdup(original);
    if (copy == NULL) {
        perror("内存分配失败");
        return 1;
    }
    
    int copyLen = strlen(copy);
    char *result = removeDuplicate(copy, copyLen);
    
    printf("原字符串:%s\n", original);
    printf("去重后:%s\n", result);
    
    // 记得释放动态分配的内存
    free(copy);
    return 0;
}

关键注意事项

  • 栈上数组的生命周期:如果在函数内定义栈上数组(比如char buf[100];),不要把这个数组的指针返回给上层函数,但在这个场景里是没问题的——因为是你传入数组给removeDuplicate,它返回的是你传入的指针,只要你的数组在后续操作时还在作用域内就行。
  • 动态分配的内存:如果用malloc/strdup分配内存,一定要记得free,避免内存泄漏。
  • 字符串终止符:前面补的str[index] = '\0'绝对不能少,否则所有依赖字符串终止符的操作都会出问题。

内容的提问来源于stack exchange,提问作者Marwen Aouiti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:07:54