周二

zeyangshuaige / 2023-05-09 / 原文

问题描述:

编写一个程序,实现字符串中的字符替换功能。假设给定一个字符串 str,将其中的字符 oldChar 全部替换成 newChar。请在不使用内置函数的前提下完成此任务。

设计思路:

本题可以采用字符串数组来存储字符串,通过循环字符串的每个字符,逐一判断是否为 oldChar,如果是,则将其替换为 newChar,最后输出替换后的字符串。

程序流程图:

st=>start: 开始
inp1=>inputoutput: 输入字符串str
inp2=>inputoutput: 输入需要替换的字符oldChar和新字符newChar
op1=>operation: 循环字符串str中的每个字符
cond1=>condition: 判断字符是否为oldChar
op2=>operation: 将oldChar替换为newChar
op3=>operation: 输出替换后的字符串
e=>end: 结束

st->inp1->inp2->op1->cond1
cond1(yes)->op2->op1
cond1(no)->op1
op1(right)->op3->e

代码实现:

 
#include <iostream>
using namespace std;

int main() {
    string str;
    char oldChar, newChar;
    cout << "请输入字符串:";
    getline(cin, str);
    cout << "请输入需要替换的字符和新字符(以空格隔开):";
    cin >> oldChar >> newChar;
    
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == oldChar) {
            str[i] = newChar;
        }
    }
    
    cout << "替换后的字符串为:" << str << endl;
    
    return 0;
}