0

I must define a Translator class that contains a capitalize method. The method will receive a StringBuffer, which contains only letters of the English alphabet and spaces, and will change it so that each of the words starts with a capital letter.

// my class I need to define

public class Main {
  public static void main(String[] args) {
    StringBuffer titlu = new StringBuffer("Why it is good to participate in competitions");
    Translator.transformaCuMajuscule(titlu);
    System.out.println(titlu); // Why It Is Good To Participate In Competitions
  }
}
Kthree
  • 156
  • 1
  • 12

1 Answers1

-1

You can write a very simple loop over each character in the string, changing it to uppercase if the previous character is a space. Something like following (note - it is not correct Java, just use it as a guide):

inputString[0] = upperCase(inputString[0]); // first is always uppercase
for(i=1; i<inputString.length; i++) {
  if (Character.isspace(inputString[i-1])
     inputString[i] = String.upperCase(inputString[i]);
}
return inputString;

It uses only one pass through the string, so it is relatively quick (you can further optimize it if needed).

EDIT: It may be a bit different if other letters need to be changed to lowercase - you can also incorporate that check in your code.

  • This does not work. 1) uses upperCase() instead of String.upperCase() 2) doesn't declare variable i 3) The method is called Character.isSpace 4) String are immutable in java and cannot be array-accessed 5) Writing the same code (upperCase) twice is bad style – Cactusroot May 08 '22 at 15:38
  • If you have read the answer text (instead of just the code), you would have noticed the words "it is not correct Java, just use it as a guide". The approach is important, and any decent IDE will point the errors. – Nikola Vanevski Jun 10 '22 at 15:38