Reputation: 4792
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?
Upvotes: 0
Views: 766
Reputation: 1500515
It's not quite right - this:
String first = str.substring(0, i - 1);
should be:
String first = str.substring(0, i);
(Think about a simple example - if i
is 1, you want to take substring(0, 1)
to get the first character; substring(0, 0)
would give an empty string.)
because the second parameter of substring
is already exclusive.
Likewise this optimization:
else if (i == str.length()) {
return str.substring(0, i);
}
should be:
else if (i == str.length() - 1) {
return str.substring(0, i);
}
You should also add argument validation.
After making those changes, this code:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(deleteCharAt("0123456789", i));
}
}
Gives this output:
123456789
023456789
013456789
012456789
012356789
012346789
012345789
012345689
012345679
012345678
Upvotes: 2
Reputation: 114
public static String deleteCharAt(String s, int pos) {
StringBuffer buf = new StringBuffer( s.length() - 1 );
buf.append( s.substring(0,pos) ).append( s.substring(pos+1) );
return buf.toString();
}
Upvotes: 1