Filtering string in java
11,992
Solution 1
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.
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);
}
}
}
}
Solution 2
Let's say your Strings are in an ArrayList called wordBank.
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
}
}
Solution 3
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));
}
Author by
regeme
Updated on June 04, 2022Comments
-
regeme almost 2 years
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!