Java String mask

Introduction

Returns a string consisting of "s", with each of the first "len" characters replaced by "mask Char" character.

public class Main {
  public static void main(String[] argv) throws Exception {
    String s = "demo2s.com";
    int len = 5;//from w  ww .  j a  v  a2s  . c  om
    char maskChar = '*';
    System.out.println(maskLeft(s, len, maskChar));
  }
  public static String maskLeft(String s, int len, char maskChar) {
    if (len <= 0) {
      return s;
    }
    len = Math.min(len, s.length());
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
      sb.append(maskChar);
    }
    sb.append(s.substring(len));
    return sb.toString();
  }

}



PreviousNext

Related