Capitalize the first letter of each word

Asked

Viewed 3,290 times

1

I want to standardize what the user typed in edittext by capitalizing the first letter of each word and the rest lower case. How do I do this?

The part that arrow the variables in the model class

Contato c = new Contato();
c.setNome(etNome.getText().toString());

2 answers

4


You can use a combination of toUpperCase() for the first letter and toLowerCase() for the rest of the word to be all minuscule. Abstracting this in a method, it looks like this:

public String toTitledCase(String str){

    String[] words = str.split("\\s");
    StringBuilder sb = new StringBuilder();

    for(int i = 0; i < words.length; i++){
        sb.append(words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase());
        sb.append(" ");
    }

    return sb.toString();
}

See working on ideone.

  • This worked by changing the first letter of the first word, I would like you to do it with all words, could help?

  • @Guilhermecostamilam words separated by a space?

  • infrequently this

  • @Guilhermecostamilam see the edition.

  • out of curiosity what is the s in the split?

  • @Guilhermecostamilam split breaks the string into an array of other strings based on a separator that you pass as parameter. In this case, I use \\s which is the representation of space in regex, but you can change to split(" "); that works normally.

  • Thanks when I use general mind split with the same space I didn’t know I could also use /s but does it make any difference? which one is better?

  • @Guilhermecostamilam the literal representation is more recommended, ie it is better to use so split(" "), although in this case there is no difference in performance.

  • For this case it is more interesting to use Stringbuilder. xD

  • 1

    @acklay altered, thanks for the tip :)

  • I put a clause if there in the middle just not to get an additional space at the end of the string str unnecessarily

Show 6 more comments

1

Thus it accepts only a compound word or phrase

public class CamelCaseConverter {

    public Object converter(String nome) {
        char[] palavras = nome.toCharArray();
        
        
        for(int i = 1; i < palavras.length; i++) {
            //convertendo todas as letras para minúsculo para casos como tEsTe = teste
            if(Character.isAlphabetic(palavras[i])) {
                palavras[i] = Character.toLowerCase(palavras[i]);
            }
            //se o carácter anterior for espaço então o atual sera maiúsculo
            if(Character.isWhitespace(palavras[i - 1])) {
                palavras[i] = Character.toUpperCase(palavras[i]);
            }
        }
        //por fim a primeira letra de toda frase ou palavra será maiúscula
        palavras[0] = Character.toUpperCase(palavras[0]);
       
        //retorna o Array de char como String
        String nomeConvertido = new String(palavras);       
        
        return nomeConvertido;
    }

}

Research sources: https://www.guj.com.br/t/iniciais-maiusculas-em-cada-palavra-da-string/114502

Browser other questions tagged

You are not signed in. Login or sign up in order to post.