如何在Java中反转String的大小写? [英] How can I invert the case of a String in Java?

查看:1200
本文介绍了如何在Java中反转String的大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改一个String,以便所有大写字符变为小写,并且所有小写字符都变为大写。数字字符只是被忽略。

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.

所以AbCdE123变成aBcDe123

so "AbCdE123" becomes "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.

推荐答案

我不知道相信有任何内置的东西(这是相对不寻常的)。这应该这样做:

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

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

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

这篇关于如何在Java中反转String的大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆