一、题目链接
http://noi.openjudge.cn/ch0107/21/
二、解题思路(Java)
三、解题思路(C++)
四、Java程序
import java.util.Scanner;
public class Main {
public String replaceWord(String text, String oldWord, String newWord) {
StringBuilder ans = new StringBuilder();
String[] words = text.split(" ");
if (words[0].equals(oldWord)) {
ans = ans.append(newWord);
}
else {
ans = ans.append(words[0]);
}
for (int i = 1; i < words.length; i++) {
if (words[i].equals(oldWord)) {
ans.append(" " + newWord);
}
else {
ans.append(" " + words[i]);
}
}
return ans.toString();
}
public static void main(String[] args) {
Main test = new Main();
Scanner input = new Scanner(System.in);
String text = input.nextLine();
String oldWord = input.next();
String newWord = input.next();
System.out.print(test.replaceWord(text, oldWord, newWord));
}
}
五、C++程序
#include <iostream>
using namespace std;
int main()
{
string text;
string oldWord;
string newWord;
getline(cin, text);
cin >> oldWord;
cin >> newWord;
int n = text.length();
int m = oldWord.length();
int k = newWord.length();
int pos = 0;
while (text.find(oldWord, pos) != text.npos)
{
pos = text.find(oldWord, pos);
if (pos == 0 && !isalpha(text[pos + m]) ||
!isalpha(text[pos - 1]) && pos + m == n ||
!isalpha(text[pos - 1]) && !isalpha(text[pos + m]))
{
text.replace(pos, m, newWord);
pos = pos + k;
}
else
{
pos++;
}
}
cout << text;
return 0;
}