Search code examples
javaloopsfor-loopcharat

Using a For Loop to set all lower case to uppercase


How do you use a for loop to set all the lower cases of a string into upper cases?

This is what I did, but I get two compiler errors,

  • The method setCharAt(int, char) is undefined for the type java.lang.String [line 7]

  • Array cannot be resolved [line 12]

public static String allUpperCases(String toEncode){
    int length = toEncode.length();

    for (int i = 0; i < length; i++){
      char ch = toEncode.charAt(i);
      if (Character.isLowerCase(ch)){
        toEncode.setCharAt(i, Character.toUpperCase(ch));
      }
    }

    return toEncode;
  }

Solution

  • You can just use a single operation!

    my_string = my_string.toUpperCase();