Reputation: 486
I want to replace ssn by certain char. for example:
public char filter = "a";
public String ssn = 123-45-6789
public replace(string ssn){
//replace ssn = aaa-aa-aaaa because filter = "a"
}
Can anyone give me an idea how to do it since it has "-" inside of the string?
Upvotes: 0
Views: 1221
Reputation: 124215
You can't modify string, since it is immutable class. But you can create new string with replaced values. So
StringBuidler
toCharArray()
can be useful here)
filter
to builder (Character.isDigit(char)
comes to mind)-
(or non-digit) append '-'
to builderYou can also try using replaceAll
and regex which will match only digits.
Upvotes: 0
Reputation: 412
To use regex with replaceAll(), you need to make your filter a String. As well, you need to return a String in your replace function. Try the following:
String filter = "a";
public String replace(String ssn)
{
return ssn.replaceAll("[0-9]",filter);
}
Upvotes: 2
Reputation: 2982
If you want to replace only the digits, try the following code:
public String replace(string ssn) {
return ssn.replaceAll("[0-9]", "a");
}
The regular expression [0-9]
defines which characters should be replaced (every "character" between 0 and 9, meaning: only digits).
Upvotes: 3