Java toString()隐藏信息

时间:2017-12-17 00:57:56

标签: java

如何让我的toString方法只返回String的某些部分,例如我有一个带有构造函数的名称和姓氏的变量。我想使用toString方法,以便它只返回每个名称的第一个字母,其中填充其余的占位符,例如' - '

var options = {
  host: YOUR_API_URL,
  port: 80,
  path: 'REST_API_END_POINT',
  method: 'YOUR_HTTP_METHOD' //POST/GET/...
};

http.request(options, function(res) {
  //Whatever you want to do with the reply...
}).end();

这样我就能得到像詹姆斯·罗伊这样的名字'J ---- R--'的输出

1 个答案:

答案 0 :(得分:3)

在类中,覆盖toString方法:

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

或更简洁:

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

replaceAll将使用令牌“ - ”替换字符串中除第一个字符外的所有字符,从而达到您想要的结果。

Here's a very helpful link for working with Regex.请注意,因为java使用'\'作为转义令牌,所以你需要使用两个,如图所示。

相关问题