This question has already been answered:

I get the String entered from the keyboard, it can contain several words and different number of spaces between them. I need to return the same string only every word with a capital letter. The number of spaces and not literals between words should remain too. I read about the substring , I understand I need to organize a beautiful rehex?

Reported as a duplicate by fori1ton , Community Spirit Jan 10 '17 at 10:09 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

2 answers 2

You can also make a "head on" solution using substring :

 String s1 = "i want to make upper case", s2 = ""; s2 = s2 + s1.substring(0, 1).toUpperCase(); //первый символ делаем заглавным for (int i = 1; i < s1.length(); i++) { // смотрим, был ли слева пробел: if (" ".equals(s1.substring(i-1, i))) s2 = s2 + s1.substring(i, i+1).toUpperCase(); else s2 = s2 + s1.substring(i, i+1); } 

Conclusion :

 i want to make upper case I Want To Make Upper Case 

An example on ideone .

  • substring is not very good - Artem Konovalov
  • @ArtemKonovalov why? TS read something about substring , I showed a solution with it. - Denis
  • because if ("" .equals (s1.substring (i-1, i))) s2 = s2 + s1.substring (i, i + 1) .toUpperCase (); - Artem Konovalov
  • We create a string, compare it, then create another string, then another one in case return, then another unifying result c s2. total 4 lines. I think it's a bit too much - Artem Konovalov
  • Thank you, it works as it should, and obviously enough for me. - Maxim Koev

On regex it will be StringBuilder , but using StringBuilder rather trivial:

 private static String toUpperCaseForFirstLetter(String text) { StringBuilder builder = new StringBuilder(text); //выставляем первый символ заглавным, если это буква if (Character.isAlphabetic(text.codePointAt(0))) builder.setCharAt(0, Character.toUpperCase(text.charAt(0))); //крутимся в цикле, и меняем буквы, перед которыми пробел на заглавные for (int i = 1; i < text.length(); i++) if (Character.isAlphabetic(text.charAt(i)) && Character.isSpaceChar(text.charAt(i - 1))) builder.setCharAt(i, Character.toUpperCase(text.charAt(i))); return builder.toString(); } 
  • Thank. Looks working. Please add comments to the code. - Maxim Koev