如何反转 Java 中字符串的大小写?
我想改变一个字符串,使所有大写字符变成小写,所有小写字符变成大写。数字字符将被忽略。
所以“AbCdE123”变成“aBcDe123”
我想一定有一种方法可以迭代字符串并翻转每个字符,或者也许有一些正则表达式可以做到这一点。
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"
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
Apache Commons StringUtils 有一个 swapCase 方法。
Apache Commons StringUtils has a swapCase method.
我不相信有任何内置的东西可以做到这一点(这相对不寻常)。但这应该可以做到:
请注意,这不会像 String.toUpperCase/String.toLowerCase 那样进行特定于区域设置的更改。它也不处理非 BMP 字符。
I don't believe there's anything built-in to do this (it's relatively unusual). This should do it though:
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 8 及以上版本:
需要注意的是反转字母大小写的代码:
Java 8 and above:
Code which is inverting the case of letter, is important to notice:
正确。
java.lang.Character
类为您提供了每个isUpperCase()
方法。对其进行测试并根据结果使用toLowerCase()
或toUpperCase()
方法。将每个结果附加到 StringBuilder 中,应该没问题。Correct. The
java.lang.Character
class provides you under each theisUpperCase()
method for that. Test on it and make use of thetoLowerCase()
ortoUpperCase()
methods depending on the outcome. Append the outcome of each to aStringBuilder
and you should be fine.根据Faraz的方法,我认为字符转换可以很简单:
Based on Faraz's approach, I think the character conversion can be as simple as:
我认为最简单的解决方案是这样的:
我认为您可以更轻松地阅读此内容,并且 StringBuilder 无论如何都有一个追加(char)方法+
Character.toUpperCase
和toLowerCase
两者都只是静态方法。我只是感觉很糟糕,因为唯一的 StringBuilder 示例也包含了 ascii 索引算术。对于那些不喜欢三元表达式的人,这里有等效的:
编辑Java 8+(StringBuilder收集器代码取自@Arun的答案)
I think the simplest solution to understand would be something like:
I think you can read through this easier and StringBuilder has an append(char) method anyways +
Character.toUpperCase
andtoLowerCase
are both just static methods. I just felt bad that the only StringBuilder example had ascii index arithmetics included as well.For those who don't like ternary expressions, here's the equivalent:
EDIT Java 8+ (StringBuilder collector code taken from @Arun's answer)
我们还可以使用 StringBuilder 对象,因为它具有字符替换方法。但是,可能需要一些额外的空间来存储 StringBuilder 对象。因此,如果空间不重要并且使解决方案易于理解,将会有所帮助。
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.
我确实意识到给定的线程非常旧,但有更好的方法来解决它:
I do realize that the given thread is very old, but there is a better way of solving it: