如果用户输入随机字母,如何更改给定字符串中的所有字母?

我试图弄清楚如何使用字符包装来根据用户输入改变字符串。 如果字符串是’鲍勃喜欢建立建筑’而用户输入’b’我必须使输出更改小写字母和大写字母bs。

这是它必须添加的内容:

System.out.print("\nWhat character would you like to replace?"); String letter = input.nextLine(); System.out.print("What character would you like to replace "+letter+" with?"); String exchange = input.nextLine(); 

怎么样:

 myString = myString.replace(letter,exchange); 

编辑:myString是要替换字母的字符串。

信件取自你的代码,这是要被替换的信件。

交换也取自你的代码,它是要替换的字母。

当然,你需要再次为大写字母和小写字母做这个,所以它将是:

 myString = myString.replace(letter.toLowerCase(),exchange); myString = myString.replace(letter.toUpperCase(),exchange); 

为了覆盖输入的字母是小写或大写的情况。

一种简单的方法是:

 String phrase = "I want to replace letters in this phase"; phrase = phrase.replace(letter.toLowerCase(), exchange); phrase = phrase.replace(letter.toUpperCase(), exchange); 

编辑:根据以下建议添加到LowCase()。

我不知道你以前的回复没有得到什么,但这与他们的代码联系起来。

  String foo = "This is the string that will be changed"; System.out.print("\nWhat character would you like to replace?"); String letter = input.nextLine(); System.out.print("What character would you like to replace "+letter+" with?"); String exchange = input.nextLine(); foo = foo.replace(letter.toLowerCase(), exchange); foo = foo.replace(letter.toUpperCase(), exchange); System.out.print("\n" + foo); // this will output the new string 

检查replace方法:

 public String replace(char oldChar, char newChar) 

返回一个新字符串,该字符串是使用newChar替换此字符串中出现的所有oldChar。

有关更多详细信息,请参阅[ String#replace ](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char,char))

编辑:

 class ReplaceDemo { public static void main(String[] args) { String inputString = "It is that, that's it."; Char replaceMe = 'i'; Char replaceWith = 't'; String newString = inputString.Replace(replaceMe.toUpperCase(), replaceWith); newString = newString.Replace(replaceMe.toLowerCase(), replaceWith); } } 

这会解决你的问题吗?