题目要求:
设计一个对字符串中的单词查找替换方法,实现对英文字符串中所有待替换单词的查找与替换。
输入格式:
首行输入母字符串,第二行输入查询的单词,第三行输入替换后的单词。
输出格式:
完成查找替换后的完整字符串
输入样例:
Although I am without you, I will always be ou you
ou
with
输出样例:
Although I am without you, I will always be with you
代码块:
import java.util.Scanner;
public class WordsReplace {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String oldSub = sc.nextLine();
String newSub = sc.nextLine();
sc.close();
String[] strs = str.split(" ");
for(int i=0;i<strs.length;i++) {
if(strs[i].equals(oldSub)) {
strs[i] = newSub;
}
}
{
String result = new String();
for(int i=0;i<strs.length;i++) {
result += strs[i]+" ";
}
System.out.println(result.trim());
}
}
}