The task is straightforward: read a line of text, replace every occurrence of one word with another, and print the updated sentence.
The input string ends at a newline and is no longer than 100 characters. It contains several words separated by single spaces, and word matching is case-sensitive.
Problem outline
There are 3 lines of input:
- Line 1: a string
scontaining multiple words - Line 2: the word
ato be replaced - Line 3: the replacement word
b
The output should be a single line where every word in s equal to a is replaced with b.
Example
Input:
You want someone to help you
You
I
Output:
I want someone to help you
Approach
Since the sentence is made up of words separated by spaces, stringstream is a convenient tool here. It can split the input line word by word, making it easy to compare each token with the target word.
The idea is:
- read the full line using
getline - read the two words
aandb - put the sentence into a
stringstream - extract each word in order
- if the current word matches
a, outputb - otherwise output the original word
Code
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s,s1,a,b;
getline(cin,s); //读入
cin>>a>>b;
stringstream ssin(s); //初始化
while(ssin>>s1){ //依次读入
if(s1==a){ //判断
cout<<b<<" ";
}
else cout<<s1<<" ";
}
return 0;
}
Notes on the code
getline(cin, s)is used because the first input line contains spaces.stringstream ssin(s)turns the entire sentence into a stream that can be read one word at a time.while (ssin >> s1)keeps extracting words until the stream is exhausted.- The comparison
s1 == ais case-sensitive, which matches the problem requirement.
One small detail: this code prints a space after every word, including the last one. In most simple judge systems this is usually accepted, but it is something to be aware of.
Common string operations
The following examples are useful when working with C++ strings:
``` string str1 = "abcdefghigklmn" ;
string str2 = str1.substr(2,5) ; //将str1从下标2开始的5个字符赋值给str2
int p1 = str1.find(str) //从最左边开始返回str1中首次出现str首字母的下标,没有时返回-1
int p2 = str1.rfind(str) //从最右边开始返回str1中首次出现str首字母的下标,没有时返回-1
string str3 = "1234.567" ;
double nums = atof(str3.c_str()) //将str3转换为float类型
int nums = atoi(ser3.c_str()) //将str3转换为int类型 ```