单词替换

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

按空格把字符串拆成单词,逐词判断是否与目标单词完全相同并替换,最后用空格拼接输出。

OJ: roj

题目 ID: 1406

难度:入门

标签:stringsimulation

创建: 2026-09-30 09:00

更新: 2026-10-05 23:02

题目描述

给定一行由单个空格分隔的单词组成的字符串 ss(长度 ≤200\le 200),以及待替换单词 aa、替换单词 bb(长度均 ≤100\le 100),单词区分大小写。输入三行依次为 ss、aa、bb,要求把 ss 中所有与 aa 完全相同的独立单词替换成 bb,其余单词不变,输出替换后的字符串。样例输入为 You want someone to help you、You、I 三行,样例输出为 I want someone to help you。

思路

题目只替换独立单词,直接在原串上做子串替换会误伤包含 aa 的长单词(例如 a="in"a=\text{"in"} 时误改 inside)。按空格把 ss 拆成单词,逐词与 aa 比较,相同则输出 bb,否则原样输出,词间用一个空格分隔。

参考代码

Python 版:

python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-30 09:00
# update_at: 2026-09-30 09:00

import sys


def replace_words(text: str, target: str, replacement: str) -> str:
    """将文本中与 target 匹配的独立单词替换为 replacement。"""
    words = text.split()
    return " ".join(replacement if word == target else word for word in words)


def solve() -> None:
    lines = sys.stdin.read().splitlines()
    if not lines:
        return
    text = lines[0]
    target = lines[1]
    replacement = lines[2]
    print(replace_words(text, target, replacement))


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-10-05 23:02
 * update_at: 2026-10-05 23:02
 */
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

typedef long long ll;

int main() {
    // s 是原始文本,target 是待替换的单词,replacement 是替换成的单词
    string s, target, replacement;
    getline(cin, s);
    getline(cin, target);
    getline(cin, replacement);

    // 按空格逐词切分:只替换与 target 完全相同的独立单词,避免子串误伤
    istringstream in(s);
    string word;
    bool first_word = true;
    while (in >> word) {
        if (!first_word) {
            cout << ' ';
        }
        first_word = false;
        if (word == target) {
            cout << replacement;
        } else {
            cout << word;
        }
    }
    cout << '\n';

    return 0;
}