Use character wrapper to code a replace a letter in a string with a new letter keeping the original case

前端 未结 3 802
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 10:42

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 chooses to replace all letter B/

3条回答
  •  日久生厌
    2021-01-28 11:38

    A simple start is to know about String.replace(char, char) in Java.

    // This addresses the example you gave in your question.
    str.replace('B', 'T').replace('b', 't');
    

    Then, you should take the user input into toReplace and replaceWith characters, figure out the uppercase/lowercase counter parts using the ASCII code and generate the arguments for the above replace method call.

    public class Main
    {
        public static void main(String[] arg) throws JSONException
        {
            String str = "Bob loves to build building";
            Scanner scanner = new Scanner(System.in);
            char toReplace = scanner.nextLine().trim().charAt(0);
            char replaceWith = scanner.nextLine().trim().charAt(0);
    
            System.out.println(str.replace(getUpper(toReplace), getUpper(replaceWith)).replace(getLower(toReplace),
                getLower(replaceWith)));
        }
    
        private static char getUpper(char ch)
        {
            return (char) ((ch >= 'A' && ch <= 'Z') ? ch : ch - ('a' - 'A'));
        }
    
        private static char getLower(char ch)
        {
            return (char) ((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch);
        }
    }
    

提交回复
热议问题