Java > Warmup-2 > stringX (CodingBat Solution)

Problem:

Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.

stringX("xxHxix") → "xHix"
stringX("abxxxcd") → "abcd"
stringX("xabxxxcdx") → "xabcdx"


Solution:

public String stringX(String str) {
  String result = "";
  int len = str.length();
  for (int i = 0; i < len; i++){
    char temp = str.charAt(i);
    if (!(i > 0 && i < len - 1 && temp == 'x'))
      result = result + temp;
      
  }
    return result;      
}


4 comments :

  1. public String stringX(String str) {

    if (str.length()<=2) return str;

    char start= str.charAt(0) ;
    char end= str.charAt(str.length()-1);
    str = str.substring(1,str.length()-1).replace("x", "");
    return start + str + end;
    }

    ReplyDelete
  2. This is the best solution:

    public String stringX(String str) {
    int len = str.length();

    if(str.length()<=2){
    return str;
    }

    if(str.startsWith("x") && str.endsWith("x")){
    String mid = str.substring(1,len-1);
    return "x" + mid.replaceAll("x", "") + "x";

    } else if(str.startsWith("x") && !str.endsWith("x")){
    String start = str.substring(1,len);
    return "x" + start.replaceAll("x", "");

    } else if(str.endsWith("x") && !str.startsWith("x")){
    String end = str.substring(0,len-1);
    return end.replaceAll("x", "") + "x";

    } else {
    return str.replaceAll("x", "");
    }
    }

    ReplyDelete
  3. With Regex

    public String stringX(String str) {
    return str.replaceAll("\\B[x]\\B", "");
    }

    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