I am trying to remove a character by index in a string. Here is a my source:
private String removeByIndex(String str, int index) {
return str.replaceFirst(String.valueOf(str.charAt(index)), "");
}
My input string is, for example, 1.05. My goal is to receive 1.5, by removing the first element after the dot.
I called this function like this
removeByIndex("1.05",Stringlength-2)
but the result is 1.
How I can solve this problem?
Try this any digit after dot will be replaced with dot only
private String removeByIndex(String str, int index) {
return str.replaceFirst("\\.[\\d]", ".");
}
If you know the index you should use String.substring(int start, int end) to cut your input. This can be folded into StringBuilder.append(String s, int start, int end):
private static String removeByIndex(String str, int index) {
StringBuilder sb = new StringBuilder();
if (index > 0) {
sb.append(str, 0, index);
}
if (index < str.length() - 1) {
sb.append(str, index + 1, str.length());
}
return sb.toString();
}
Or as pointed by pascalpuetz:
private static String removeByIndex(String str, int index) {
return new StringBuilder(str).deleteCharAt(index).toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With