简体   繁体   English

屏蔽字符串时保留空白

[英]preserving whitespace when masking a String

I want to preserve the white space in the String while it is being masked. 我想在字符串被屏蔽时保留字符串中的空白。 Below is the code I wrote for masking the string but it doesn't take into account that my some of my strings in my Arraylist have white space. 下面是我为屏蔽字符串而编写的代码,但没有考虑到Arraylist中的某些字符串有空格。

for (int i=0;i<secretWord.length();i++){
    System.out.print("*");
}

You can simply check whether a character is space or not! 您只需检查一个字符是否为空格!

for (int i=0;i<secretWord.length();i++){
    if(secretWord.charAt(i)!=' ')
    {
        System.out.print("*");
    }
    else
    {
        System.out.print(" ");
     }
}
System.out.print(secretWord.replaceAll("\\S","*"));

(在正则表达式中, \\S表示不是空格字符的单个字符。)

I think you are looking for a * for a character and space for a space to mask the string. 我认为您正在寻找一个*字符和一个空格来掩盖字符串。
Do it like this: 像这样做:

for (int i=0 ; i<secretWord.length() ; i++){
        if(Character.isWhitespace(charAt(i))){
             System.out.print(charAt(i));
         }else{
             System.out.print("*");
          }
    }

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

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