java 在java中过滤字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16121739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:57:58  来源:igfitidea点击:

Filtering string in java

javaarraysstringsubstring

提问by regeme

It's not about filtering bad words so get in. Imagine that you have list of strings named as abcd,abcde,abcdef,abfg,abdc if a user gives string abc as filter in ConsoleProgram abcd,abcde and abcdef will be printed out. I thought about using substring but I couldn't achieved it does anybody have any idea .. note that I am new to java and not competent thanks!

这不是关于过滤坏词所以进入。想象一下,如果用户在 ConsoleProgram 中提供字符串 abc 作为过滤器 abcd,abcde 和 abcdef 将被打印出来,那么你有一个名为 abcd,abcde,abcdef,abfg,abdc 的字符串列表。我想过使用子字符串,但我无法实现它是否有人有任何想法..请注意,我是 Java 新手,不胜任,谢谢!

回答by alvarodev

The first thing you need is learn about String Regex, maybe here: http://docs.oracle.com/javase/tutorial/essential/regex/. Try out the next simply code.

您需要的第一件事是了解 String Regex,可能在这里:http: //docs.oracle.com/javase/tutorial/essential/regex/。尝试下一个简单的代码。

public class StringMatcher {

    public static void main(String[] args) {
        String[] words = new String[]{"abcd", "abcde", "abcdef", "abfg", "abdc"};
        String filter = "abc";

        for (String word : words) {
            if (word.matches(filter + "(.*)")) {
                System.out.println("This pass the filter: " + word);
            }
        }
    }
}

回答by Achintya Jha

Try this: If the item in list contains the string inputted by user it will get printed.

试试这个:如果列表中的项目包含用户输入的字符串,它将被打印出来。

input = "abc";
for(int i = 0 ; i < list.size(); i++){
  if (list.get(i).contains(input))
    System.out.println(list.get(i));
}

回答by Joel Christophel

Let's say your Strings are in an ArrayList called wordBank.

假设您的字符串位于名为 wordBank 的 ArrayList 中。

for(String i : wordBank) { //loops through the array with 'i' being current index
    if(i.contains("abc")) { //checks if index contains filter String
        System.out.println(i); //prints out index if filter String is present
    }
}

回答by Milo? Luka?ka

use String.contains()- it returns true when string contains given char sequence, see string-javadoc

使用String.contains()- 当字符串包含给定的字符序列时返回 true,请参阅string-javadoc