每个句子中带有符号的单词首字母大写

huangapple go评论77阅读模式
英文:

Capitalize first letter in each word with symbols in sentence

问题

我有一个存储人们写下的字符串的数据库。这些字符串例如定义了电影的名称。

为了解决重复项和其他一些问题,我做的是无论用户输入什么,它都会使每个单词的第一个字母大写。通过这种方式,所有的字符串都会以相同的方式保存。

我使用的方法是:

String[] words = query.split( "\\s+" );
for (int i = 0; i < words.length; i++) {
    String Word = words[i].replaceAll( "[^\\w]", "" );
    words[i] = Word.substring( 0, 1 ).toUpperCase() + Word.substring( 1 );
}
query = TextUtils.join( " ", words );

然而,当我尝试输入类似 "Tom & Jerry" 这样的内容时,我遇到了问题。

在这种情况下,&amp; 导致了错误。我是否只需要设置条件来检查每个字符,比如 &amp;、(、)、$ 等等?

英文:

I have a database that stores strings that people wrote. Those string for example defines the name of movies.

In order to overcome duplicates and some other things, I did that no matter what the user typed, it will make every first letter capital. In that manner, all of the strings will be saved in the same way.

The way I do it is by using:

String[] words = query.split( &quot;\\s+&quot; );
for (int i = 0; i &lt; words.length; i++) {
    String Word = words[i].replaceAll( &quot;[^\\w]&quot;, &quot;&quot; );
    words[i] = Word.substring( 0, 1 ).toUpperCase() + Word.substring( 1 );
}
query = TextUtils.join( &quot; &quot;, words );

However, I faced a problem when I tried to type something like: Tom & Jerry.

In that case, I got an error with the &amp;. Do I just need to set if conditions to check for every letter such as &amp;, (, ), $ and so on?

答案1

得分: 1

toUpperCase 处理非字母字符没问题,它会直接返回相同的字符。你代码的问题在于它假设每个 word 都是非空的,在你移除特殊字符后,这个假设不再成立。

长话短说,只需保留特殊字符,就没问题了:

for (int i = 0; i < words.length; i++) {
    String word = words[i];
    words[i] = word.substring(0, 1).toUpperCase() + word.substring(1);
}
英文:

toUpperCase handles non-letter characters just fine, and just returns the same character. The problem with your code is that it assumes each word is non-empty, which is no longer true after you remove the special characters.

To make a long story short, just keep the special characters, and you should be OK:

for (int i = 0; i &lt; words.length; i++) {
    String word = words[i];
    words[i] = word.substring( 0, 1 ).toUpperCase() + word.substring( 1 );
}

huangapple
  • 本文由 发表于 2020年9月21日 02:49:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63982518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定