你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

7-3 字符串替换 (10 分)

2021/12/15 23:48:36

将文本文件中指定的字符串替换成新字符串。 由于目前的OJ系统暂时不能支持用户读入文件,我们编写程序从键盘输入文件中的内容,当输入的一行为end时,表示结束。end后面有两个字符串,要求用第二个字符串替换文本中所有的第一个字符串。

输入格式:

Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology. The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

end (表示结束)

Institute (第一个字符串,要求用第二个字符串替换)

University (第二个字符串)

输出格式:

Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

输入样例:

Xi’an Institute of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.
The Institute is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.
end
Institute
University

输出样例:

Xi’an University of Posts and Telecommunications is co-designed and implemented by the People’s Government of Shaanxi Province and the Ministry of Industry and Information Technology.The University is located in Xi’an, a historic city in Northwest China, famous for its magnificent ancient culture.

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
        String str = "";
		String str1;
		String str2 = "";
		String str3 = "";
		while(true) {
			str1 = in.nextLine();
			if (str1.contentEquals("end")) {
				break;
			}else {
				str = str.concat(str1) + '\n';
			}
		}
		str2 = in.next();
		str3 = in.next();
		str = str.replace(str2,str3);
		System.out.print(str);
	}
}

  很多同学可能一开始写的总是有一个测试点有问题,可能是没有在每次连接字符串时添加一个换行符,因为系统认为输入字符串时,一个回车就代表一行,所以导致试了很多次仍然有问题,一开始我也是被这个问题所困扰,最后只需要加上换行符就行。题中的输出样例有一定的误导作用,没有表现出一个输入例子就得换一行的说明。