Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete char at position in string

Tags:

java

string

Currently, I am working on a project that requires to delete a char at a set position in a string. Is there a simple way to do this?

like image 411
Meh Avatar asked Nov 30 '13 19:11

Meh


2 Answers

Use a StringBuilder, which has the method deleteCharAt(). Then, you can just use stringBuilder.toString() to get your string.

EDIT, here's an example:

public static void main(String[] args) {
    String string = "bla*h";
    StringBuilder sb = new StringBuilder(string);
    sb.deleteCharAt(3);
    // Prints out "blah"
    System.out.println(sb.toString());
}
like image 71
Alex Vulaj Avatar answered Oct 23 '22 20:10

Alex Vulaj


Strings are immutable ! But to accomplish your task, you can

  1. Copy the substring from the start of the string to the character that has to be deleted
  2. Copy the substring from the character that has to be deleted to the end of the String.
  3. Append the second String to the first one.

For example, let's say you have to remove the third character:

String input = "Hello, World";
String first = input.substring(0, 3);
String second = input.substring(4);
String result = first + second;
like image 22
Konstantin Yovkov Avatar answered Oct 23 '22 19:10

Konstantin Yovkov