Java – Doubling each letter in a String

charjavawhile-loop

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++;
  }

Best Answer

String s="mystring".replaceAll(".", "$0$0");

The method String.replaceAll uses the regular expression syntax which is described in the documentation of the Pattern class, where we can learn that . matches “any character”. Within the replacement, $number refers to numbered “capturing group” whereas $0 is predefined as the entire match. So $0$0 refers to the matching character two times. As the name of the method suggests, it is performed for all matches, i.e. all characters.