Case Conversion

I'm trying to run a program that switches capital letters to lowercase and vice versa. So "ABcDefG" would output "abCdEFg". This is my code:

String str = "UPPER lower";
int counter;
char ch;


for(counter = 0; counter < str.length(); counter++)
{
if(Character.isLowerCase(str.charAt(counter)))
{
ch = Character.toUpperCase(str.charAt(counter));
str = str.replace(str.charAt(counter), ch);
}

else
{
ch = Character.toLowerCase(str.charAt(counter));
str = str.replace(str.charAt(counter), ch);
}

}

System.out.println(str);

I want the output to be "upper LOWER". Instead I get "uPPER LOWER". I'm new to this but I can't figure out why this won't work. I've also tried if(str.charAt(counter) >= 'A' && str.charAt(counter) <= 'Z'), but I get the same result.

If someone can explain to me what I clearly don't understand about char/string or if/else or for loops, I would be eternally grateful.

Thanks you very much.

Comments

  • Sike,
    You were on the right track with looping, but used a String method, [link=jar:file:///C:/Program%20Files/Java/api%20docs/jdk-6u10-docs.zip!/docs/api/java/lang/String.html#replace%28char,%20char%29]replace()[/link], that doesn't do what you need it to do.
    Using a [link=http://download.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html]StringBuilder[/link] rather than a String and the setCharAt() will get the job done.
    [code]public class CaseConversion {

    public static void main(String[] args) {
    StringBuilder str = new StringBuilder("UPPER lower");
    int counter;
    char ch;
    for (counter = 0; counter < str.length(); counter++) {
    if (Character.isLowerCase(str.charAt(counter))) {
    ch = Character.toUpperCase(str.charAt(counter));
    str.setCharAt((counter), ch);
    } else {
    ch = Character.toLowerCase(str.charAt(counter));
    str.setCharAt((counter), ch);
    }

    }

    System.out.println(str);
    }
    }[/code]
    regards, se52
  • Wow, thank you very much, se52. This is exactly what I was looking for. I had seen StringBuilder on some other Java sites but I couldn't figure out how to use it. I also clearly misunderstood the purpose of replace. Thanks again. This was incredibly helpful.
  • This post has been deleted.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories