How to replace all characters in a Java string with stars

前端 未结 9 1855
不思量自难忘°
不思量自难忘° 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:23

    How abt creating a new string with the number of * = number of last string char?

    StringBuffer bf = new StringBuffer();
    for (int i = 0; i < source.length(); i++ ) {
        bf.append('*');
    }
    
    0 讨论(0)
  • 2020-12-01 08:29

    Don't use regex at all, count the String length, and return the according number of stars.

    Plain Java < 8 Version:

    int len = str.length();
    StringBuilder sb = new StringBuilder(len);
    for(int i = =; i < len; i++){
        sb.append('*');
    }
    return sb.toString();
    

    Plain Java >= 8 Version:

    int len = str.length();
    return IntStream.range(0, n).mapToObj(i -> "*").collect(Collectors.joining());
    

    Using Guava:

    return Strings.repeat("*", str.length());
    // OR
    return CharMatcher.ANY.replaceFrom(str, '*');
    

    Using Commons / Lang:

    return StringUtils.repeat("*", str.length());
    
    0 讨论(0)
  • 2020-12-01 08:30
    System.out.println("foobar".replaceAll(".", "*"));
    
    0 讨论(0)
提交回复
热议问题