用字符串Java中的全名替换所有特殊字符的最佳方法是什么?
我想将字符串中的所有特殊字符转换为它们的全名
示例:
输入:什么是堆栈溢出
输出:什么是堆栈溢出问号
我用replaceall()
来做,但是有没有更简单的方法来做,因为我必须为每个特殊字符写一行
text = text.replaceAll("\\.", " Fullstop ");
text = text.replaceAll("!", " Exclamation mark ");
text = text.replaceAll("\"", " Double quote ");
text = text.replaceAll("#", " Hashtag ");
...
# 1 楼答案
你可以用一句话来表达
您可以链接字符串操作,即一个字符串操作的结果可以通过链接传递给下一个操作,如下所示:
输出:
# 2 楼答案
使用
IntStream
可以一次完成…或根据Joop Eggen的想法改编(但保留原文)
获取:
Input‹COLON›‹SPACE›What‹SPACE›is‹SPACE›stack‹SPACE›overflow‹QUESTION MARK›
# 3 楼答案
这里的一种方法是维护一个包含所有符号及其名称替换的hashmap。然后,对输入字符串执行正则表达式迭代并进行所有替换
这张照片是:
上面的方法看起来有点冗长,但实际上所有的核心替换逻辑都发生在一行
while
循环中。如果您使用的是Java8,那么也可以使用Matcher
流方法,但逻辑基本相同# 4 楼答案
您可以使用
Stream
:# 5 楼答案
查看内置的Unicode名称:
使用
toLowerCase
/大写,您可以获得一个完整的&;紧凑的结果