javaregexspringstring-utils

How to make conditions StringUtils less than specific character in Java


I wrote a String class that masking username something like;

input --> Johny Holloway expecting output ---> J***y H***y

and its working.

However I like to change my code if user input name and surname less than 3 character

example; Name BR ---> B***R ; surName --> 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;
  }  

Solution

  • Treat the cases differently, for 2 chars it can be the same.

    To make the code better, do not use char (UTF-16) but Unicode code points. Sometimes Unicode code points, symbols, use 2 chars: Chinese, emoji. 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.

    StringBuilder is faster, and its appendCodePoint is usefull here.