【问题标题】:Identifying Java String characters either its lower or upper case识别 Java 字符串字符的小写或大写
【发布时间】:2021-03-05 18:42:58
【问题描述】:
A   123
B   456
a   789
b   091

String str = "A quick BROWN Fox jumps over the Lazy Dog";

如果a为大写则为123,如果a为小写则为789;

如何在字符串中找到大写或小写的“a”或“b”,然后将其转换为数值?

【问题讨论】:

  • 这很容易解决。发布您迄今为止尝试过的任何内容,让我们知道您遇到的问题。

标签: java string


【解决方案1】:

Apache Commons StringUtils:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#replaceEachRepeatedly-java.lang.String-java.lang.String:A-java.lang.String:A-

我会像这样使用 StringUtils(库是我们的朋友):

String [] originalLetters = {"A", "B", "a", "b"};
String [] mappings = {"123", "456", "789", "091"};
String str = "A quick BROWN Fox jumps over the Lazy Dog";
String output = StringUtils.replaceEachRepeatedly(str, originalLetters, mappings);

希望对您有所帮助...警告 - 我没有尝试编译这个。

【讨论】:

    【解决方案2】:

    你可以这样做:

        String str = "A quick BROWN Fox jumps over the Lazy Dog";
    
        String result = str.replace("A", "123").replace("a", "789").replace("B", "456").replace("b", "091");
    
        System.out.println("result = " + result);
    

    这将输出以下内容:

    result = 123 quick 456ROWN Fox jumps over the L789zy Dog
    

    【讨论】:

    • 如果我以String str = "A quick BROWN Fox jumps over the Lazy Dog & a Cat"; 开头,那么str.replace("&","&#38").replace("A", "123").replace("a", "789").replace("B", "456").replace("b", "091"); 会产生123 quick 456ROWN Fox jumps over the L789zy Dog &#38 789 C789t
    • 了解str.replace("&","&#38") 不会更改字符串。它创造了一个新的。您需要将其返回值分配给一个变量。例如,str = str.replace("&", "&#38")
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2016-01-25
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多