Shingix
Shingix

Reputation: 21

Java toString() Hiding information

How do I get my toString method to return only certain parts of a String, for example I have a variable for a name and surname with a constructor. I want to use a toString method so that it returns only the first letter of each name filling the rest with a placeholder for example a '-'

enter code here

private String foreame = null;
private String surname = null;

public FullName(String forename, String surname) 
{
   this.forename = forename;
   this.surname = surname;
}

So that I could get an output like 'J---- R--' for the name James Roy

Upvotes: 1

Views: 369

Answers (1)

Zachary
Zachary

Reputation: 1703

In the class, Override the toString method as such:

@Override
public String toString() {
    return forename.replaceAll("\\B\\w", "-")) + " " + surname.replaceAll("\\B\\w", "-"));   
}

or, more concisely:

@Override
public String toString() {
    return (forename + " " + surname).replaceAll("\\B\\w", "-");
}

The replaceAll will replace all but the first character in the Strings with the token "-", achieving your desired outcome.

Here's a very helpful link for working with Regex. Note that because java uses the '\' as an escape token, you need to use two as shown.

Upvotes: 3

Related Questions