How to replace all characters in a Java string with stars

前端 未结 9 1854
不思量自难忘°
不思量自难忘° 2020-12-01 07:32

I want to replace all the characters in a Java String with * character. So it shouldn\'t matter what character it is, it should be replaced with a *

相关标签:
9条回答
  • 2020-12-01 08:03
    public String allStar(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (int i = 0; i < s.length(); i++) {
            sb.append('*');
        }
        return sb.toString();
    }
    
    0 讨论(0)
  • 2020-12-01 08:04

    Recursive method

    String nCopies(String s, int n) {
        return n == 1 ? s.replaceFirst(".$", "") : nCopies(s + s, --n);
    }
    
    0 讨论(0)
  • 2020-12-01 08:15
        String text = "Hello World";
        System.out.println( text.replaceAll( "[A-Za-z0-9]", "*" ) );
    

    output : ***** *****

    0 讨论(0)
  • 2020-12-01 08:17

    There may be other faster/better ways to do it, but you could just use a string buffer and a for-loop:

    public String stringToAsterisk(String input) {
        if (input == null) return "";
    
        StringBuffer sb = new StringBuffer();
        for (int x = 0; x < input.length(); x++) {
            sb.append("*");
        }
        return sb.toString();
    }
    

    If your application is single threaded, you can use StringBuilder instead, but it's not thread safe.

    I am not sure if this might be any faster:

    public String stringToAsterisk(String input) {
        if (input == null) return "";
    
        int length = input.length();
        char[] chars = new char[length];
        while (length > 0) chars[--length] = "*";
        return new String(chars);
    }
    
    0 讨论(0)
  • 2020-12-01 08:21

    Java 11 and later

    str = "*".repeat(str.length());
    

    Note: This replaces newlines \n with *. If you want to preserve \n, see solution below.

    Java 10 and earlier

    str = str.replaceAll(".", "*");
    

    This preserves newlines.

    To replace newlines with * as well in Java 10 and earlier, you can use:

    str = str.replaceAll("(?s).", "*");
    

    The (?s) doesn't match anything but activates DOTALL mode which makes . also match \n.

    0 讨论(0)
  • 2020-12-01 08:21

    Without any external library and without your own loop, you can do:

    String input = "Hello";
    char[] ca = new char[input.length()];
    Arrays.fill(ca, '*');
    String output = new String(ca);
    

    BTW, both Arrays.fill() and String(char []) are really fast.

    0 讨论(0)
提交回复
热议问题