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

如何替换字符串数组内每个字符串中指定字符的所有出现位置

C++ 字符串数组单字符批量替换实现

实现思路

  • 第一层循环遍历字符串数组的所有元素,拿到每一个待处理的字符串
  • 第二层循环遍历当前字符串的每个字符,和要替换的目标字符比对,匹配成功就直接替换为新字符
  • 所有元素处理完成后即可输出结果

完整实现代码

#include <iostream>
#include <string>
using namespace std;

int main() {
    // 原始数组定义
    string A[5] = {"hello","my","name","is","lukas"};
    // 定义要替换的旧字符和新字符
    char old_char = 'l';
    char new_char = 'x';
    int arr_len = sizeof(A)/sizeof(A[0]);

    // 执行替换逻辑
    for(int i=0; i<arr_len; i++) {
        // 遍历当前字符串的每个字符
        for(int j=0; j<A[i].size(); j++) {
            if(A[i][j] == old_char) {
                A[i][j] = new_char;
            }
        }
    }

    // 格式化输出结果
    cout << "{";
    for(int i=0; i<arr_len; i++) {
        cout << "\"" << A[i] << "\"";
        if(i != arr_len-1) cout << ",";
    }
    cout << "}" << endl;
    return 0;
}

运行输出

{"hexxo","my","name","is","xukas"}

简化写法

可以使用STL内置算法简化替换逻辑,需额外引入头文件#include <algorithm>,把单字符串的遍历替换代码改成:

replace(A[i].begin(), A[i].end(), old_char, new_char);

功能和手动遍历完全一致。

内容的提问来源于stack exchange,提问作者Vasiliauskas Lukas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:05