Java > Recursion-1 > noX (CodingBat Solution)

Problem:

Given a string, compute recursively a new string where all the 'x' chars have been removed.

noX("xaxb") → "ab"
noX("abc") → "abc"
noX("xx") → ""


Solution:

public String noX(String str) {
  if (str.equals("")) return str;
  if (str.charAt(0) == 'x') return noX(str.substring(1));
  else return str.charAt(0) + noX(str.substring(1));
}


2 comments :

  1. public String noX(String str) {
    int i = str.indexOf('x');
    if(i==-1)return str;
    str = str.substring(0,i)+str.substring(i+1);
    return noX(str);
    }

    ReplyDelete
  2. public String noX(String str) {
    if(str.indexOf("x")<0) return str;
    return noX(str.substring(0, str.indexOf("x")) + str.substring(str.indexOf("x")+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