Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of char from string

I can use this:

String str = "TextX Xto modifyX"; str = str.replace('X','');//that does not work because there is no such character '' 

Is there a way to remove all occurrences of character X from a String in Java?

I tried this and is not what I want: str.replace('X',' '); //replace with space

like image 887
evilReiko Avatar asked Jan 01 '11 23:01

evilReiko


People also ask

How do you remove all occurrences of a character from a string in C++?

Approach: The idea is to use erase() method and remove() function from C++ STL. Below is the syntax to remove all the occurrences of a character from a string. Below is the implementation of the above approach: C++

How do you remove all instances of a string from a string?

Remove all instances of a character from string using filter() and join() In Python, you can use the filter() function to filter all the occurrences of a characters from a string.

How do I remove all instances from a char in a string Python?

Remove All Occurrences of a Character From a String in Python Using the filter() Function. We can also use the filter() function with the join() method and lambda function to remove the occurrences of a character from a string in Python.


2 Answers

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", ""); 
like image 178
LukeH Avatar answered Sep 23 '22 23:09

LukeH


Using

public String replaceAll(String regex, String replacement) 

will work.

Usage would be str.replace("X", "");.

Executing

"Xlakjsdf Xxx".replaceAll("X", ""); 

returns:

lakjsdf xx 
like image 27
Michael Wiles Avatar answered Sep 22 '22 23:09

Michael Wiles