简体   繁体   English

如何用星号替换 Java 字符串中的所有字符

[英]How to replace all characters in a Java string with stars

I want to replace all the characters in a Java String with * character.我想用*字符替换 Java 字符串中的所有字符。 So it shouldn't matter what character it is, it should be replaced with a * .所以它是什么字符无关紧要,应该用*替换。

I know there are heaps of examples there on internet but have not one that replaces every character and I have tried myself but no success.我知道互联网上有很多例子,但没有一个可以取代每个角色,我自己也尝试过,但没有成功。

Java 11 and later Java 11 及更高版本

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

Note: This replaces newlines \\n with * .注意:这会将换行符\\n替换为* If you want to preserve \\n , see solution below.如果您想保留\\n ,请参阅下面的解决方案。

Java 10 and earlier Java 10 及更早版本

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

This preserves newlines.这会保留换行符。

To replace newlines with * as well in Java 10 and earlier, you can use:要在 Java 10 及更早版本中用*替换换行符,您可以使用:

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

The (?s) doesn't match anything but activates DOTALL mode which makes . (?s)不匹配任何内容,但会激活DOTALL模式,这使得. also match \\n .也匹配\\n

Don't use regex at all, count the String length, and return the according number of stars.完全不要使用正则表达式,计算字符串长度,并返回相应的星数。

Plain Java < 8 Version:纯 Java < 8 版本:

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

Plain Java >= 8 Version:纯 Java >= 8 版本:

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 :使用Commons/Lang

return StringUtils.repeat("*", str.length());
System.out.println("foobar".replaceAll(".", "*"));
public String allStar(String s) {
    StringBuilder sb = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
        sb.append('*');
    }
    return sb.toString();
}

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('*');
}

There may be other faster/better ways to do it, but you could just use a string buffer and a for-loop:可能还有其他更快/更好的方法来做到这一点,但您可以只使用字符串缓冲区和 for 循环:

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.如果您的应用程序是单线程的,您可以改用 StringBuilder,但它不是线程安全的。

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);
}

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.顺便说一句, Arrays.fill()String(char [])都非常快。

Recursive method递归方法

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

output : ***** *****输出 : ***** *****

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM