Java——替换字符串中的字符

题意:
1、输入一个字符串
2、用户选择下一步操作是“quit”(退出)还是“replace all”(替换字符),如果输入错误,则提示,并重新输入选择
3、如果选择的是替换,提示用户输入要被替换的是哪一个字符
4、对字符进行判断,如果在字符串中,则继续输入新的要替换的字符,否则,打印输出error
5、程序对字符串中所有跟用户的字符一样的字符进行替换

import java.util.Scanner;


public class Change {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner get=new Scanner(System.in);
		System.out.print("Enter a string (up to 25 characters) to be transformed:");
		String top=get.nextLine();
		while(true) {
			System.out.println();
			System.out.println("Enter your command(quit, replace all): ");
			String str=get.nextLine();
			if(str.compareToIgnoreCase("quit")==0) {
				break;
			}else if(str.compareToIgnoreCase("replace all")==0) {
				System.out.println("------------------------------------");
				System.out.print("Enter the character to replace: ");
				char old_s=get.nextLine().charAt(0);
				String old=String.valueOf(old_s);
				if(top.contains(old)) {
					System.out.print("Enter the new character:");
					char new_s=get.nextLine().charAt(0);
					
					for(int i=0;i<top.length();i++) {
						if(top.charAt(i)==old_s) {
							//String 是固定的,不可改变,StringBuilder是动态的可变的
							StringBuilder strBuilder=new StringBuilder(top);
							strBuilder.setCharAt(i, new_s);
							top=strBuilder.toString();
						}					
					}
				}else {
					System.out.println("Error, "+old_s+" is not in the string.");
				}
			
			}else {
				System.out.println("Sorry, that command is valid. Please type one of the options.");
			}
			System.out.println("------------------------------------");
			System.out.println("Your new sentence is:"+top);
			
		}
		get.close();				
	}

}

修改字符串时,不能直接对String字符串进行操作修改,因为String是固定,不可修改的,只能先转化为StringBuilder,修改后再转化为字符串进行输出——
StringBuilder strBuilder=new StringBuilder(top); strBuilder.setCharAt(i, new_s); top=strBuilder.toString();

在这里插入图片描述

发布了75 篇原创文章 · 获赞 52 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/WU2629409421perfect/article/details/90680898