For example, "Jorge Aragão Silva" returns me "J A S"
For example, "Jorge Aragão Silva" returns me "J A S"
In the title of the question you are asked to pick up only the capital letters of the words. In the example in the body of the text there are spaces, but I have @ André Filipe .
You can use regular expressions to remove non-uppercase letters:
String nomeCompleto = "Jorge Aragão Silva";
return nomeCompleto.replaceAll("\P{Lu}", "");
The replaceAll
" of the string in Java will replace any part that matches the pattern (first argument) with the substitute. The default I passed was \P{Lu}
.
It consists of the denied pattern of the Lu
property. What does that mean? Basically, if a letter is within the Lu
pattern, it will be ignored; otherwise, if it is in Lu
, it will match the default and therefore will be replaced.
The Lu
pattern is the case of Unicode uppercase letters. Therefore, anything that is not uppercase Unicode will be removed.
If I wanted a pattern that would satisfy the Lu
property, I would use \p{Lu}
with p
same lowercase. The P
indicates that the property described {between braces} will be denied.
In substitution, I placed two against% s of% s because of how Java treats counter slash in strings. So, if I write \
, Java will understand that I wanted to type the string \n
. Already \n
Java interprets as line break. To explicitly tell Java that I want a counter bar \n
and a \
uppercase, I used P
.
Sources that helped me:
String nomeCompleto = "Jorge Aragão Silva";
StringBuilder iniciaisEmMaiusculo = new StringBuilder();
for (char letra : nomeCompleto.toCharArray()) {
if (Character.isUpperCase(letra)) {
iniciaisEmMaiusculo.append(letra);
}
}
return iniciaisEmMaiusculo.toString(); //Retornará a String "JAS"
Good studies!
Using for after the split you can
Take a look
String x = "Shojibur rahman";
String[] myName = x.split(" ");
String saida = "";
for (int i = 0; i < myName.length; i++) {
String s = myName[i].toUpperCase();
saida += s.charAt(0)+" ";
}
System.out.println(saida);
}
I hope I have helped
Simple example
String nome = "Jorge Aragão Silva".toUpperCase();
String iniciais = "";
for (int i = 0; i < nome.length(); i++){
char caractere = nome.charAt(i);
if(i == 0)
iniciais+=caractere;
if(caractere == ' ')
iniciais+=nome.charAt(i+1);
}