[String] Ybt_ word replacement

General idea

Here is a paragraph of English, ending with a new line.
I'll give you two more words. I want you to replace all the words in that paragraph of English with the word below.
case sensitive


solution

Simple string function use. Here we use s.erase(), s.find(), and s.insert(). The three functions
(respectively clear, search, insert)
pay attention to input...
90 points measured in YbtOj. It seems that there is a bug in the input (?) The
bug code

bug代码1getline(cin, s);
    cin >> s1 >> s2;
    s = " " + s + " ";
bug代码2
    c = getchar();
    while (c != '\n') {
    
    
        s = s + c;
        c = getchar();
    }
    s = " " + s + " ";
    cin >> s1 >> s2;

[Unexplained]. Anyway, change it to the following.


Code

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
string s, s1, s2;
char c;
int main() {
    
    
    c = getchar();
    while ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == ' ') {
    
    
        s = s + c;
        c = getchar();
    }
    s = " " + s + " ";  
    //前后加空格,便于分辨文段中所找到的字串是否是一个单词,而不是单词的一部分
    cin >> s1 >> s2;
    s1 = " " + s1 + " ";
    s2 = " " + s2 + " ";
    while (s.find(s1, 0) != string::npos) {
    
      //能找到
        int k = s.find(s1, 0);  //替换
        s.erase(k, s1.size());
        s.insert(k, s2);
    }
    cout << s.substr(1, s.size() - 1) << endl;  //去空格输出
}

Guess you like

Origin blog.csdn.net/qq_42937087/article/details/114991573