Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove character by index in Java

Tags:

java

string

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?

like image 602
BekaKK Avatar asked Sep 25 '26 01:09

BekaKK


2 Answers

Try this any digit after dot will be replaced with dot only

private String removeByIndex(String str, int index) {
    return str.replaceFirst("\\.[\\d]", ".");
}
like image 55
Abhishek Singh Avatar answered Sep 26 '26 14:09

Abhishek Singh


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();
}
like image 31
Karol Dowbecki Avatar answered Sep 26 '26 14:09

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!