The issue is needing to replace a single character in a given string while maintaining the other characters in the string.
The code is:
i
You almost did it, just add a counter in your loop:
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);
You can use command.replaceAll("and", "a")
for example
You can use StringBuilder to replace a single character at some index, like this:
int charIndex = baseString.indexOf(charToBeReplaced);
StringBuilder baseStringBuilder = new StringBuilder(baseString);
baseStringBuilder.setCharAt(num2replace, secondChar);
Read more about StringBuilder's setCharAt() method here.