字符替换

GitHub跳转原题关系图返回列表

调用字符串 replace 将目标字符的全部出现替换为指定字符。

OJ: noi_openjudge

题目 ID: ch0107-08

难度:入门

标签:字符串模拟python

日期: 2026-07-30 23:01

题意

把字符串中指定字符的所有出现替换成另一个字符。

思路

text.replace(old, new) 返回替换全部出现后的新字符串,正好对应题意。

代码

Python代码

python
text, old, new = input().split()
print(text.replace(old, new))

C++代码

cpp
#include <cstdio>
#include <cstring>
#define maxn 500

int n;
char str[maxn];
char t1[10];
char t2[10];

int main(){
    scanf("%s",str+1);
    scanf("%s",t1+1);
    scanf("%s",t2+1);
    int len = strlen(str+1);
    int i;
    for (i=1;i<=len;i++){
        if( str[i] == t1[1]){
            str[i] = t2[1];
        }
    }
    printf("%s\n",str+1);
    return 0;
}

复杂度

时间复杂度和输出空间均为 O(n)O(n)

总结

全量字面替换使用 replace 即可,无需手写循环。