mask a string - Java java.lang

Java examples for java.lang:String Format

Description

mask a string

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        int len = 2;
        System.out.println(mask(str, len));
    }// w w w .jav a 2 s .c  o m

    private static final char SEPARATOR_CHAR_ASTERISK = '*';

    public static String mask(String str, int len) {
        if (str == null || str.length() == 0) {
            return str;
        }
        if (len >= str.length()) {
            char[] mask = repeatAsterisk(str.length());
            return new String(mask);
        }
        int startIndex = (str.length() - len) / 2;
        char[] mask = repeatAsterisk(len);

        char[] chars = str.toCharArray();
   
        System.arraycopy(mask, 0, chars, startIndex, mask.length);
  
        return new String(chars);
    }

    public static String mask(String str, int beginIndex, int endIndex) {
        if (str == null || str.length() == 0) {
            return str;
        }
        if (beginIndex < 0) {
            beginIndex = 0;
        }
        if (endIndex > str.length()) {
            endIndex = str.length();
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        if (str.length() == 1) {
            return String.valueOf(SEPARATOR_CHAR_ASTERISK);
        }

        char[] chars = str.toCharArray();
        char[] mask = repeatAsterisk(subLen);
    
        System.arraycopy(mask, 0, chars, beginIndex, subLen);
   
        return new String(chars);
    }

    private static char[] repeatAsterisk(int len) {
        char[] chars = new char[len];
        for (int i = 0; i < len; i++) {
            chars[i] = SEPARATOR_CHAR_ASTERISK;
        }
        return chars;
    }
}

Related Tutorials