I am trying to figure out how to use character wrapping to mutate a string based on user input. If string is \'Bob loves to build building\' and user enters \'b\' I have to mak
Im not sure what you dont get about the previous replies but this ties them to your code.
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
how about:
myString = myString.replace(letter,exchange);
EDIT: myString is the string you want to replace the letter in.
letter is taken from your code, it is the letter to be replaced.
exchange is also taken from your code, it is the string that letter is to be replace with.
Of course you would need to do this again for the upper case letter and lower case so it would be:
myString = myString.replace(letter.toLowerCase(),exchange);
myString = myString.replace(letter.toUpperCase(),exchange);
In order to cover the case where the entered letter is either lower or uppercase.
A simplistic approach would be:
String phrase = "I want to replace letters in this phase";
phrase = phrase.replace(letter.toLowerCase(), exchange);
phrase = phrase.replace(letter.toUpperCase(), exchange);
EDIT: Added toLowerCase() as per suggestion below.
Check replace
method:
public String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
For more details see [String#replace
](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char, char))
EDIT:
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);
}
}
Does that solve your problem?