英文:
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" 这样的内容时,我遇到了问题。
在这种情况下,&
导致了错误。我是否只需要设置条件来检查每个字符,比如 &、(、)、$
等等?
英文:
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( "\\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 );
However, I faced a problem when I tried to type something like: Tom & Jerry.
In that case, I got an error with the &
. Do I just need to set if conditions to check for every letter such as &, (, ), $
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 < words.length; i++) {
String word = words[i];
words[i] = word.substring( 0, 1 ).toUpperCase() + word.substring( 1 );
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论