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

ⅰ亾dé卋堺 提交于 2019-12-20 05:45:06

问题


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/b with T/t how do I need to code it to get 'Tom loves to tuild tuildings'?


回答1:


I think there is a String class built-in replace function.

String text = "Bob loves to build building";
text = text.replace("B","T").replace("b","t");

something like this ?




回答2:


Your question is unclear (how 'b' becomes 'm' in Bob -> Tom?). However, to run case insensitive replace you should do something like this:

String text ="Bob loves to build building";
String b = "b";

Pattern p = Pattern.compile(b, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);

String outText = m.replaceAll("T");



回答3:


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


来源:https://stackoverflow.com/questions/12399724/use-character-wrapper-to-code-a-replace-a-letter-in-a-string-with-a-new-letter-k

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!