Search code examples
javastringuppercase

Capitalize first letter in each word with symbols in sentence


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?


Solution

  • 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 );
    }