Last Updated:

How to remove a character in a string in Java

Since strings in Java are immutable, there is no direct functionality to remove a character in a string. However, to solve this problem, you can create a new line without this character.

How to remove a character in a string

 

Since strings in Java are immutatable, we will have to construct a new string from the old one.

 

Let's say we have the string "Hello wWorld!" and we need to remove the extra "w":

 

String s = "Hello wWorld!";

To do this, first find the position of the symbol "w":

 

int i = s. indexOf("w");

The character "w" is in the sixth position in the search line. Next, construct a new line using the substring method:

 

String s2 = s. substring(0, i) + s. substring(i + 1);

Here we created a new line from the search string, copying from the search string all the characters before "w" and the characters after "w":

 

System. out. println(s2); // Hello World!

Source code

 

public class RemoveCharFromString {
public static void main(String[] args) {
String s = "Hello wWorld!";
 
int i = s. indexOf("w"); // 6
String s2 = s. substring(0, i) + s. substring(i + 1);
 
System. out. println(s2); // Hello World!
}
}

Conclusion

Although we can't change the contents of a string, we can create a new string from the original string using helper methods: String.substring, String.indexOf.