I am going through the CodingBat exercises for Java. I have got up to this problem which asks:
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.
I wanted to solve this by checking each character from the second up to the penultimate of the string. If the character is x, replace it with an empty character. Here is my code:
public String stringX(String str) {
String newStr = "";
for (int i = 1; i < str.length()-1; i++) {
if (str.indexOf('x') == i) {
newStr += str.replace('x', '\u0000');
}
}
return newStr;
}
The result of this is that it doesn't seem to return any of the string passed in, if the string begins with x:
System.out.println(test.stringX("xxHxix"));
returns (blank)
System.out.println(test.stringX("abxxxcd"));
returns abcd
System.out.println(test.stringX("xabxxxcdx"));
returns (blank)
I really can't figure out what's going on but I want to be able to understand it before just looking at the answer.
Is it problematic to concatenate a char into a string? Should I use substring instead?
Aucun commentaire:
Enregistrer un commentaire