If user inputs random letter, how do I change all

2020-05-10 11:17发布

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 make the out put change both the lower case and upper case letter bs.

This is what it must add on to:

 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();

标签: java
4条回答
叛逆
2楼-- · 2020-05-10 11:42

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 
查看更多
一纸荒年 Trace。
3楼-- · 2020-05-10 11:44

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.

查看更多
家丑人穷心不美
4楼-- · 2020-05-10 11:56

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.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-05-10 11:57

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?

查看更多
登录 后发表回答