RLe
RLe

Reputation: 486

Replace digits by character in String

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

Answers (3)

Pshemo
Pshemo

Reputation: 124215

You can't modify string, since it is immutable class. But you can create new string with replaced values. So

  • create StringBuidler
  • iterate over all characters of ssn (toCharArray() can be useful here)
    • if char is digit append filter to builder (Character.isDigit(char) comes to mind)
    • if char is - (or non-digit) append '-' to builder
  • convert builder toString

You can also try using replaceAll and regex which will match only digits.

Upvotes: 0

Mi_Onim
Mi_Onim

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

mastov
mastov

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

Related Questions