使用字符包装器代码替换字符串中的字母,并使用保留原始案例的新字母

试图弄清楚如何使用字符包装来根据用户输入改变字符串。 如果字符串是’Bob喜欢建造建筑’并且用户选择用T / t替换所有字母B / b,我如何编码以获得’Tom喜欢Tuild tuildings’?

我认为有一个String类内置替换函数。

 String text = "Bob loves to build building"; text = text.replace("B","T").replace("b","t"); 

这样的事情?

你的问题不清楚(鲍勃如何’b’成为’m’ – >汤姆?)。 但是,要运行不区分大小写的替换,您应该执行以下操作:

 String text ="Bob loves to build building"; String b = "b"; Pattern p = Pattern.compile(b, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(text); String outText = m.replaceAll("T"); 

一个简单的开始是了解Java中的String.replace(char, char)

 // This addresses the example you gave in your question. str.replace('B', 'T').replace('b', 't'); 

然后,您应该将用户输入转换为toReplace并替换带有字符,使用ASCII代码计算出大写/小写计数器部分,并为上述替换方法调用生成参数。

 public class Main { public static void main(String[] arg) throws JSONException { String str = "Bob loves to build building"; Scanner scanner = new Scanner(System.in); char toReplace = scanner.nextLine().trim().charAt(0); char replaceWith = scanner.nextLine().trim().charAt(0); System.out.println(str.replace(getUpper(toReplace), getUpper(replaceWith)).replace(getLower(toReplace), getLower(replaceWith))); } private static char getUpper(char ch) { return (char) ((ch >= 'A' && ch <= 'Z') ? ch : ch - ('a' - 'A')); } private static char getLower(char ch) { return (char) ((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch); } }