In this Q&A, we'll go over options available to search for a string within a string.
On top of that, StringUtils class that's part of Apache Commons Lang provides methods to search string ignoring case and to search for one of many strings.
See demo code below
package com.javahowdoi.string;
import org.apache.commons.lang3.StringUtils;
import static junit.framework.TestCase.assertEquals;
public class SearchDemo {
public static void main(String[] args) {
String s = "Pennsylvania";
String s1 = "van";
String s2 = "Van";
assertEquals( "indexOf equals 7", 7, s.indexOf(s1) );
assertEquals( "contains match ", true, s.contains(s1) );
assertEquals( "contains don't match ", false, s.contains(s2) );
assertEquals( "containsIgnoreCase match ", true, StringUtils.containsIgnoreCase(s, s2) );
assertEquals( "containsAny match ", true, StringUtils.containsAny(s, s1, s2) );
}
}
Comments
Post a Comment