java 一段英文_将空格分隔的单词中每个单词的首字母改成大写.,使用Java 8 Stream用不同的分隔符将字符串中单词的首字母大写...

I need to capitalize first letter in every word in the string, BUT it's not so easy as it seems to be as the word is considered to be any sequence of letters, digits, "_" , "-", "`" while all other chars are considered to be separators, i.e. after them the next letter must be capitalized.

Example what program should do:

For input: "#he&llo wo!r^ld"

Output should be: "#He&Llo Wo!R^Ld"

There are questions that sound similar here, but there solutions really don't help.

This one for example:

String output = Arrays.stream(input.split("[\\s&]+"))

.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))

.collect(Collectors.joining(" "));

As in my task there can be various separators, this solution doesn't work.

解决方案

It is possible to split a string and keep the delimiters, so taking into account the requirement for delimiters:

word is considered to be any sequence of letters, digits, "_" , "-", "`" while all other chars are considered to be separators

the pattern which keeps the delimiters in the result array would be: "((?<=[^-`\\w])|(?=[^-`\\w]))":

[^-`\\w]: all characters except -, backtick and word characters \w: [A-Za-z0-9_]

Then, the "words" are capitalized, and delimiters are kept as is:

static String capitalize(String input) {

if (null == input || 0 == input.length()) {

return input;

}

return Arrays.stream(input.split("((?<=[^-`\\w])|(?=[^-`\\w]))"))

.map(s -> s.matches("[-`\\w]+") ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s)

.collect(Collectors.joining(""));

}

Tests:

System.out.println(capitalize("#he&l_lo-wo!r^ld"));

System.out.println(capitalize("#`he`&l+lo wo!r^ld"));

Output:

#He&l_lo-wo!R^Ld

#`he`&L+Lo Wo!R^Ld

Update

If it is needed to process not only ASCII set of characters but apply to other alphabets or character sets (e.g. Cyrillic, Greek, etc.), POSIX class \\p{IsWord} may be used and matching of Unicode characters needs to be enabled using pattern flag (?U):

static String capitalizeUnicode(String input) {

if (null == input || 0 == input.length()) {

return input;

}

return Arrays.stream(input.split("(?U)((?<=[^-`\\p{IsWord}])|(?=[^-`\\p{IsWord}]))")

.map(s -> s.matches("(?U)[-`\\p{IsWord}]+") ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s)

.collect(Collectors.joining(""));

}

Test:

System.out.println(capitalizeUnicode("#he&l_lo-wo!r^ld"));

System.out.println(capitalizeUnicode("#привет&`ёж`+дос^βιδ/ως"));

Output:

#He&L_lo-wo!R^Ld

#Привет&`ёж`+Дос^Βιδ/Ως

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值