3

I am trying to write code which will change given string into alt case.

"hello" ---> "HeLlO"
"legend of zelda" ---> "LeGeNd oF ZeLdA"

This is what I have so far:

public String altCase(String text) {
    String replace = "";

    for (int i = 0; i < text.length(); i++) {
        if (i % 2 == 0) {
            replace = text.replace(Character.toString(text.charAt(i)),
                    Character.toString(text.charAt(i)).toLowerCase());
        } else {
            replace = text.replace(Character.toString(text.charAt(i)),
                    Character.toString(text.charAt(i)).toUpperCase());
        }
    }

    return replace;
}

replace turns into text and nothing else changes.

What is causing this, and how do I fix it?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Big Boss
  • 73
  • 1
  • 3
  • 12

2 Answers2

1

Try this:

public String altCase(String text)
{
    String replace = "";

    for(int i = 0; i < text.length(); i++)
    {
        if(i%2 == 0)
        {
            replace += Character.toString(text.charAt(i)).toLowerCase());
        }
        else
        {
            replace += Character.toString(text.charAt(i)).toUpperCase());
        }
    }

    return replace;
}

Just append either the lower case or upper case character to the existing string. I'd also have a look at StringBuilder as well. See here

Community
  • 1
  • 1
Davie Brown
  • 717
  • 4
  • 23
  • I would also suggest using the StringBuilder for better performance (especially if you may have a large String) https://docs.oracle.com/javase/tutorial/java/data/buffers.html +1 – MaVRoSCy Mar 13 '16 at 23:58
  • An explanation on why his attempt fails would be worth extra bonus points – D. Ben Knoble Mar 14 '16 at 00:56
1

Simply the code by:

  • turn everything to lowercase
  • flip every other letter to uppercase
  • use a StringBuilder to make the code simpler

Then it's just a few lines, like this:

public static String altCase(String text){
    StringBuilder result = new StringBuilder(text.toLowerCase());
    for(int i = 0; i < text.length(); i+= 2)
        result.setCharAt(i, Character.toUpperCase(text.charAt(i)));
    return result.toString();
}

Note how I don't convert the character to a String then call toUpperCase(), I call the utility method Character.toUpperCase() on the character directly.

Bohemian
  • 412,405
  • 93
  • 575
  • 722