I created this method deleteCharAt in order to remove a char from a string by its index:
public String deleteCharAt(String str, int i) {
if (i == 0) {
return str.substring(1);
}
else if (i == str.length()) {
return str.substring(0, i-1);
}
String first = str.substring(0, i - 1);
String second = str.substring(i+1);
return first + second;
}
However it’s not working as expected, I think it may be because I’m not understanding how the substring function works.
Does this look correct? Will this code remove the i-th character from a string successfully? Or did I mess up the substring function?
It’s not quite right – this:
should be:
(Think about a simple example – if
iis 1, you want to takesubstring(0, 1)to get the first character;substring(0, 0)would give an empty string.)because the second parameter of
substringis already exclusive.Likewise this optimization:
should be:
You should also add argument validation.
After making those changes, this code:
Gives this output: