如何在 Java 中反转字符串的大小写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1729778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:59:09  来源:igfitidea点击:

How can I invert the case of a String in Java?

javastringcasecase-sensitive

提问by James

I want to change a String so that all the uppercase characters become lowercase, and all the lower case characters become uppercase. Number characters are just ignored.

我想更改一个字符串,以便所有大写字符变为小写,所有小写字符变为大写。数字字符将被忽略。

so "AbCdE123" becomes "aBcDe123"

所以“AbCdE123”变成了“aBcDe123”

I guess there must be a way to iterate through the String and flip each character, or perhaps some regular expression that could do it.

我想必须有一种方法可以遍历 String 并翻转每个字符,或者某些正则表达式可以做到这一点。

采纳答案by Jon Skeet

I don't believe there's anything built-in to do this (it's relatively unusual). This should do it though:

我不相信有任何内置的东西可以做到这一点(这是相对不寻常的)。这应该这样做:

public static String reverseCase(String text)
{
    char[] chars = text.toCharArray();
    for (int i = 0; i < chars.length; i++)
    {
        char c = chars[i];
        if (Character.isUpperCase(c))
        {
            chars[i] = Character.toLowerCase(c);
        }
        else if (Character.isLowerCase(c))
        {
            chars[i] = Character.toUpperCase(c);
        }
    }
    return new String(chars);
}

Note that this doesn't do the locale-specific changing that String.toUpperCase/String.toLowerCase does. It also doesn't handle non-BMP characters.

请注意,这不会执行 String.toUpperCase/String.toLowerCase 所做的特定于语言环境的更改。它也不处理非 BMP 字符。

回答by Jacob Mattison

Apache Commons StringUtils has a swapCasemethod.

Apache Commons StringUtils 有一个swapCase方法。

回答by BalusC

I guess there must be a way to iterate through the String and flip each character

我想必须有一种方法可以遍历字符串并翻转每个字符

Correct. The java.lang.Characterclass provides you under each the isUpperCase()method for that. Test on it and make use of the toLowerCase()or toUpperCase()methods depending on the outcome. Append the outcome of each to a StringBuilderand you should be fine.

正确的。该java.lang.Character班为您提供以下各isUpperCase()该方法。对其进行测试并根据结果使用toLowerCase()toUpperCase()方法。将每个的结果附加到 a StringBuilder,你应该没问题。

回答by Faraz Arif

I do realize that the given thread is very old, but there is a better way of solving it:

我确实意识到给定的线程很旧,但有更好的解决方法:

class Toggle
{ 
    public static void main()
    { 
        String str = "This is a String";
        String t = "";
        for (int x = 0; x < str.length(); x++)
        {  
            char c = str.charAt(x);
            boolean check = Character.isUpperCase(c);
            if (check == true)
                t = t + Character.toLowerCase(c);
            else
                t = t + Character.toUpperCase(c);
        }
        System.out.println (t);
    }
}

回答by Vivek P

We can also use a StringBuilder object, as it has character replacing methods. However, it might take some extra space to store the StringBuilder object. So, it will help if space does not matter and keep the solution simple to understand.

我们也可以使用 StringBuilder 对象,因为它具有字符替换方法。但是,可能需要一些额外的空间来存储 StringBuilder 对象。因此,如果空间无关紧要并保持解决方案易于理解,这将有所帮助。

String swapCase(String text) {
    StringBuilder textSB = new StringBuilder(text);
    for(int i = 0; i < text.length(); i++) {
        if(text.charAt(i) > 64 && text.charAt(i) < 91)
            textSB.setCharAt(i, (char)(text.charAt(i) + 32));
        else if(text.charAt(i) > 96 && text.charAt(i) < 123)
            textSB.setCharAt(i, (char)(text.charAt(i) - 32));
    }
    return textSB.toString();
}

回答by CStockton

Based on Faraz's approach, I think the character conversion can be as simple as:

基于Faraz的方法,我认为字符转换可以像这样简单:

t += Character.isUpperCase(c) ? Character.toLowerCase(c) : Character.toUpperCase(c);

回答by Arun

Java 8 and above:

Java 8 及更高版本:

String myString = "MySampleString123";
System.out.println(myString.chars().map(c -> Character.isLetter(c) ? c ^ ' ' : c).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString());

Code which is inverting the case of letter, is important to notice:

反转字母大小写的代码很重要,请注意:

Character.isLetter(c) ? c ^ ' ' : c

回答by Kinowe

public class ReverseCase {
    public  static void main(String[] args){ 
        char[] char_arr = args[0].toCharArray();
        for (int i = 0; i < char_arr.length; i++) {
            if (Character.isLowerCase(char_arr[i])) {
                char_arr[i] = Character.toUpperCase(char_arr[i]);
            }else {
                char_arr[i] = Character.toLowerCase(char_arr[i]);
            }
        }
        String reversed = new String(char_arr);
        System.out.println(reversed);
    }
}