简体   繁体   English

如何使条件StringUtils小于Java中的特定字符

[英]How to make conditions StringUtils less than specific character in Java

I wrote a String class that masking username something like;我写了一个 String 类来屏蔽用户名;

input --> Johny Holloway expecting output ---> J***y H***y输入 --> Johny Holloway 期待输出 ---> J***y H***y

and its working.及其工作。

However I like to change my code if user input name and surname less than 3 character但是,如果用户输入的姓名和姓氏少于 3 个字符,我喜欢更改我的代码

example;例子; Name BR ---> B***R ;名称 BR ---> B***R ; surName --> KL ---> K***L姓 --> KL ---> K***L

How to change my code according to above example如何根据上面的示例更改我的代码

My code is below;我的代码如下;

public class MaskWords {

  public String mask(String str) {

    if (StringUtils.isBlank(str)) {
      return str;
    }

    String out = "";
    for (String d : str.split("\\s+")) {
      String startChar = d.substring(0, 1);
      String endChar = d.substring(d.length() - 1, d.length());
      out = out + startChar + "***" + endChar + " ";
    }
    return out.trim();
  }

  public List<String> mask(List<String> str) {
    List<String> maskedStringList = new ArrayList<>();
    for (String stringToMask : str) {
      maskedStringList.add(mask(stringToMask));
    }
    return maskedStringList;
  }  

Treat the cases differently, for 2 chars it can be the same.以不同的方式对待案例,对于 2 个字符,它可以是相同的。

To make the code better, do not use char (UTF-16) but Unicode code points.为了使代码更好,不要使用字符(UTF-16),而是使用 Unicode 代码点。 Sometimes Unicode code points, symbols, use 2 chars: Chinese, emoji.有时 Unicode 代码点、符号使用 2 个字符:中文、表情符号。 So more general would be:所以更一般的是:

StringBuilder out = new StringBuilder(str.length + 10);
for (String d : str.split("\\s+")) {
    int codePoints = d.codePointCount(0, d.length());
    if (codePoints >= 2) {
        int startChar = d.codePointAt(0);
        int endChar = d.codePointBefore(d.length());
        out.appendCodePoint(startChar).append("***").appendCodePoint(endChar).append(' ');
    } else if (codePoints == 1) {
        out.append(d).append("***").append(' ');
        // Or: out.append("* ");
    }
}
return out.toString().trim();

With 1 code point, I made X*** (better * ) but if so desired, X***X would be covered by the first if, for > 0.使用 1 个代码点,我创建了X*** (更好的* ),但如果需要, X***X将被第一个覆盖,如果 > 0。

StringBuilder is faster, and its appendCodePoint is usefull here. StringBuilder更快,它的appendCodePoint在这里appendCodePoint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM