Search code examples
javaarraylistuppercaselowercase

Changing size of letters in a given string


i've got code that changes lower case latters to upper case and the other way around. What is the faster way of doing it that what i wrote?

public static String flipcase(String text) {

   ArrayList<Character> arry2 = new ArrayList<Character>();
   char[] array = text.toCharArray();
   char x = ' ';
   char y = ' ';

   for (int i = 0; i <array.length; i++) {
       if (Character.isLowerCase(array[i])) {
           x = Character.toUpperCase(array[i]);
           arry2.add(x);
       } else if (Character.isUpperCase(array[i])){
           y =  Character.toLowerCase(array[i]);
           arry2.add(y);
       } else if (Character.isSpace(array[i])) {
           arry2.add(array[i]);
       }
   }
   StringBuilder result = new StringBuilder(arry2.size());
   for (Character c : arry2) {
       result.append(c);
   }
   String output = result.toString();

   return output;
}

public static void main(String[] args) {
   System.out.println(flipcase("To jest Ten FLIP Case"));
}

Solution

  • There are two reasons why I'd say your code will be slow:

    1. You're putting the changed letters into a List: this necessarily means that you are boxing the chars to Characters, which takes time if you're doing a lot of them.
    2. You're putting the changed letters into a list, and then copying them into a StringBuilder. You could simply put them straight into the StringBuilder.

    But I'd say it is faster just to manipulate directly in array, and use new String(array) at the end.

    char[] array = text.toCharArray();
    int j = 0;
    for (int i = 0; i <array.length; i++) {
       if (Character.isLowerCase(array[i])) {
           array[j++] = Character.toUpperCase(array[i]);
       } else if (Character.isUpperCase(array[i])) {
           array[j++] = Character.toLowerCase(array[i]);
       } else if (Character.isSpace(array[i])) {
           array[j++] = array[i];
       }
    }
    return new String(array, 0, j);
    

    toCharArray() returns a copy of the char array backing the string, so you're free to modify it.

    This is basically what StringBuilder is doing; it just does it with one fewer "layer".