javawhile-loopchar

Doubling each letter in a String


I'm doing a project for Java 1, and I'm completely stuck on this question.

Basically I need to double each letter in a string.

"abc"  ->  "aabbcc"
"uk"   ->  "uukk"
"t"    ->  "tt"

I need to do it in a while loop in what is considered "Java 1" worthy. So i'm guessing that this means more of a problematic approach.

I know that the easiest way for me to do this, from my knowledge, would be using the charAt method in a while loop, but for some reason my mind can't figure out how to return the characters to another method as a string.

Thanks

[EDIT] My Code (wrong, but maybe this will help)

int index = 0;
  int length = str.length();
  while (index < length) {
      return str.charAt(index) + str.charAt(index);
      index++;
  }

Solution

  • Yeah, a for loop would really make more sense here, but if you need to use a while loop then it would look like this:

    String s = "abc";
    String result = "";
    int i = 0;
    while (i < s.length()){
        char c = s.charAt(i);
        result = result + c + c;
        i++;
    }