by vladimirfomene on 4/18/17, 8:04 AM with 5 comments
Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.
withoutX("xHix") → "Hi" withoutX("xHi") → "Hi" withoutX("Hxix") → "Hxi"
Here is my solution(quick code):
public String withoutX(String str) { //handles single x characters if(str.length() == 1 && str.charAt(0) == 'x'){ str = ""; //handles empty strings }else if(str.length() == 0){ str = ""; //handles all other cases }else{ if(str.charAt(0) == 'x'){ str = str.substring(1); }
if(str.charAt(str.length() - 1) == 'x'){
str = str.substring(0, str.length() - 1);
}
}
return str;
}Here is the solution from coding bat: public String withoutX(String str) { if (str.length() > 0 && str.charAt(0) == 'x') { str = str.substring(1); }
if (str.length() > 0 && str.charAt(str.length()-1) == 'x') {
str = str.substring(0, str.length()-1);
}
return str;
// Solution notes: check for the 'x' in both spots. If found, use substring()
// to grab the part without the 'x'. Check that the length is greater than 0
// each time -- the need for the second length check is tricky to see.
// One could .substring() instead of .charAt() to look into the string.
}
by klibertp on 4/18/17, 8:34 AM
public String withoutX(String str) { //handles single x characters
if(str.length() == 1 && str.charAt(0) == 'x'){
str = "";
//handles empty strings
}else if(str.length() == 0){
str = "";
//handles all other cases
}else{
if(str.charAt(0) == 'x'){
str = str.substring(1);
}
if(str.charAt(str.length() - 1) == 'x'){
str = str.substring(0, str.length() - 1);
}
}
return str;
}
public String withoutX(String str) {
if (str.length() > 0 && str.charAt(0) == 'x') {
str = str.substring(1);
}
if (str.length() > 0 && str.charAt(str.length()-1) == 'x') {
str = str.substring(0, str.length()-1);
}
return str;
// Solution notes: check for the 'x' in both spots. If found, use substring()
// to grab the part without the 'x'. Check that the length is greater than 0
// each time -- the need for the second length check is tricky to see.
// One could .substring() instead of .charAt() to look into the string.
}
by brudgers on 4/18/17, 4:02 PM
Good luck.
by ankurdhama on 4/18/17, 8:46 AM