Java > String-2 > doubleChar (CodingBat Solution)

Problem:

Given a string, return a string where for every char in the original, there are two chars.

doubleChar("The") → "TThhee"
doubleChar("AAbb") → "AAAAbbbb"
doubleChar("Hi-There") → "HHii--TThheerree"

Solution:

public String doubleChar(String str) {
int len = str.length();
String new_str = "";
for (int i = 0; i < len; i++) {
new_str += str.substring(i,i+1) + str.substring(i, i+1);
}
return new_str;
}


6 comments :

  1. public String doubleChar(String str) {
    String newString = "";
    for(int i=0; i<str.length(); i++){
    newString = newString + str.charAt(i)+str.charAt(i);
    }
    return newString;
    }

    ReplyDelete
  2. public String doubleChar(String str) {
    return (str.isEmpty())? "": "" + str.charAt(0) + str.charAt(0) +doubleChar(str.substring(1));
    }

    ReplyDelete
  3. public String doubleChar(String str) {
    if(str.isEmpty()){
    return ""
    }
    return str.charAt(0) + str.charAt(0) +doubleChar(str.substring(1));
    }

    ReplyDelete
  4. public String doubleChar(String str) {
    if(str.isEmpty()){
    return "";
    }
    return "" + str.charAt(0) + str.charAt(0) +doubleChar(str.substring(1));
    }

    ReplyDelete
  5. public String doubleChar(String str) {
    if(str.isEmpty()){
    return "";
    }
    return "" + str.charAt(0) + str.charAt(0) +doubleChar(str.substring(1));
    }

    ReplyDelete
  6. public String doubleChar(String str) {
    return (str.isEmpty())?
    str:
    "" + str.charAt(0) + str.charAt(0) +doubleChar(str.substring(1));
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact