Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute characters in string

Tags:

java

string

I am trying to create a string which substitutes all spaces for a * but I can't figure out exactly how to do that. Can anyone help?

String phrase = new String ("This is a String test."); 
like image 261
Chickadee Avatar asked May 31 '11 01:05

Chickadee


People also ask

How do I replace two characters in a string?

Python: Replace multiple characters in a string using the replace() In Python, the String class (Str) provides a method replace(old, new) to replace the sub-strings in a string. It replaces all the occurrences of the old sub-string with the new sub-string.

How do you replace a character in a string in Python?

The Python replace() method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace() method is commonly used in data cleaning.

Can you use replace on a string?

replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do you replace a specific character in a string in Java?

Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.


4 Answers

Mystring = Mystring.Replace(' ', '*');

like image 41
Adam Dymitruk Avatar answered Sep 21 '22 14:09

Adam Dymitruk


String phrase = new String ("This is a String test."); 

/*Replace the Spaces with the *, */

String finalString = phrase.Replace(' ', '*');    

System.out.println(finalString);
like image 36
gmhk Avatar answered Sep 23 '22 14:09

gmhk


Assuming it's Java, you can use the String.replace method:

phrase = phrase.replace(' ', '*');
like image 101
Bala R Avatar answered Sep 23 '22 14:09

Bala R


Do not create String with new operator. In Java, String is a special class. So

    String phrase = "This is a String test.";

is enough. Creating String with new operator will create string twice.

like image 25
Dmitry Avatar answered Sep 22 '22 14:09

Dmitry