替换String中的单个字符

问题是需要替换给定字符串中的单个字符,同时保持字符串中的其他字符。

代码是:

if(command.equalsIgnoreCase("replace single")) { System.out.println("Enter the character to replace"); String char2replace = keyboard.nextLine(); System.out.println("Enter the new character"); String secondChar = keyboard.nextLine(); System.out.println("Which " + char2replace + " would you like to replace?"); int num2replace = keyboard.nextInt(); for(int i=0; i< bLength; i++) { if(baseString.charAt(i)== char2replace.charAt(0)) { baseString = baseString.substring(0, i) + secondChar + baseString.substring(i + 1); } 

你几乎做到了,只需在循环中添加一个计数器:

 int num2replace = keyboard.nextInt(); int count = 0; for (int i = 0; i < bLength; i++) { if (baseString.charAt(i) == char2replace.charAt(0)) { count++; if (count == num2replace){ baseString = baseString.substring(0, i) + secondChar + baseString.substring(i + 1); break; } } if (char2replace.length() > 1) {//you need move this out of loop System.out.println("Error you can only enter one character"); } } System.out.println(baseString); 

例如,您可以使用command.replaceAll("and", "a")

您可以使用StringBuilder替换某个索引处的单个字符,如下所示:

 int charIndex = baseString.indexOf(charToBeReplaced); StringBuilder baseStringBuilder = new StringBuilder(baseString); baseStringBuilder.setCharAt(num2replace, secondChar); 

在这里阅读有关StringBuilder的setCharAt()方法的更多信息。