如何用星号替换Java字符串中的所有字符 [英] How to replace all characters in a Java string with stars

查看:685
本文介绍了如何用星号替换Java字符串中的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 * 字符替换Java String中的所有字符。所以它应该是什么字符并不重要,应该用 * 替换。

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 *.

我知道那里互联网上有大量的例子,但没有一个替代每个角色,我已经尝试过但没有成功。

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及以后



Java 11 and later

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

注意:这将取代换行符 \ n * 。如果您想保留 \ n ,请参阅下面的解决方案。

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

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

保留换行符。

要在Java 10及更早版本中用 * 替换换行符,您可以使用:

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

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

(?s)不会匹配任何东西,但激活 DOTALL 模式使也匹配 \ n

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

这篇关于如何用星号替换Java字符串中的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆