简体   繁体   English

如何忽略字符串/流中的某些字符?

[英]How to ignore certain characters in a String / Stream?

Let's say, I write some code to print out "Hello World."比方说,我编写了一些代码来打印“Hello World”。

Could I use some sort of ignore list of characters to be ignored from my print string (in this case Hello World).我可以使用某种忽略字符列表来从我的打印字符串中忽略(在本例中为 Hello World)。 For instance, I want to remove the r in "hello wo r ld" so that the output is "Hello Wold"例如,我想删除“hello wo r ld”中的 r,以便输出为“Hello Wold”

I have a value that I am using.我有一个正在使用的值。 I have the following characters: &, \\, and *.我有以下字符:&、\\ 和 *。

I think one of these characters is causing me to have some of my values ignored.我认为这些角色之一导致我忽略了我的一些价值观。

Normally I would just test this myself, but I am not able to do this at this time.通常我会自己测试这个,但我现在无法做到这一点。

No idea why you would want to do this, but writing a method to do that isn't all that hard...不知道你为什么要这样做,但编写一个方法来做到这一点并不难......

public static void printlnWithIgnores(String toPrint, Set<Character> ignore) {
    for(char c : toPrint.toCharArray()) {
        if(! ignore.contains(c)) {
            System.out.print(c);
        }
    }
    System.out.println();
}

As for that happening within a string because of a character literal, I'm not sure that it's possible.至于由于字符文字而在字符串中发生的情况,我不确定这是否可能。 Some tests:一些测试:

  • \\b (the backspace character) doesn't work \\b (退格字符)不起作用
  • (char)127 (the delete character) doesn't work (char)127 (删除字符)不起作用

That said, if your passwords can have backslashes ( \\ ) in them, that can absolutely be a problem.也就是说,如果您的密码中可以包含反斜杠 ( \\ ),那绝对是一个问题。 \\ in Java is used to denote a special character, with the following character. \\在Java中用来表示一个特殊字符,后面跟着一个字符。 The string "nnn" is just "nnn" , but "n\\nn" is字符串"nnn"只是"nnn" ,但"n\\nn"

 n
 n

Because \\n represents a newline, the third n is lost.因为\\n代表换行符,所以第三个 n 丢失了。

There are many specialty characters denoted like this, but more importantly your passwords really can't have \\ in them without causing issues.有许多这样表示的特殊字符,但更重要的是,您的密码中确实不能包含\\而不会引起问题。 Either you're getting an escape character if the following character if the following character with a backslash is legal (and \\1 actually is) , or it won't print if it's not legal.如果后面带有反斜杠的字符是合法的(实际上\\1是合法的 ,则您会得到一个转义字符,或者如果不合法则不会打印。

Solving this same problem using Java 8:使用 Java 8 解决同样的问题:

    List<String> ignore = Arrays.asList("r", "2", "3");
    String text = "Hello world 1 2 3";
    text=toRemove.stream().map(toRem-> (Function<String,String>)s->s.replaceAll(toRem, "")).reduce(Function.identity(), Function::andThen).apply(text);
    System.out.println(text);

Output:输出:

Hello wold 1  
  

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

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