package com.ethjava;
import java.util.ArrayList;
import java.util.Scanner;
public class wordswap {
public static void main(String[] args) {
//自己的答案,用Arraylist将所有的word都存进去,再打印的时候,做一个交换处理
Scanner sc = new Scanner(System.in);
ArrayList<String> arrList = new ArrayList<String>();
while(sc.hasNext()) {
String str = sc.nextLine();
String[] word=str.split(" ");
for(int i=0;i<word.length;i++){
arrList.add(word[i]);}
String old=sc.nextLine();
arrList.add(old);
String newnew=sc.nextLine();
arrList.add(newnew);
for(int i=0; i<arrList.size()-2;i++) {
if(arrList.get(i).equals(old))
System.out.print(newnew+" ");
else System.out.print(arrList.get(i)+" ");
}
}
/*范例答案
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String s = sc.nextLine().trim();
String old = sc.nextLine().trim();
String newnew = sc.nextLine().trim();
String[] words = s.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].equals(old)) System.out.print(newnew+" ");
else System.out.println(words[i]+" ");
}
}
sc.close();
*/
}
}
输入:
You want someone to help you You I
用I 替换YOU
I want someone to help you

本文介绍了如何在Java中进行单词替换操作,特别是在字符串中将'I'替换为'YOU'的示例。
1934

被折叠的 条评论
为什么被折叠?



