배열의 문자열이 포함되어 있는지 확인하려면 어떻게 문자열을 테스트합니까?
사용하는 대신
if (string.contains(item1) || string.contains(item2) || string.contains(item3))
답변
편집 : 다음은 Java 8 Streaming API를 사용한 업데이트입니다. 훨씬 더 깨끗합니다. 여전히 정규 표현식과 결합 할 수 있습니다.
public static boolean stringContainsItemFromList(String inputStr, String[] items) {
return Arrays.stream(items).parallel().anyMatch(inputStr::contains);
}
또한 입력 유형을 배열 대신 List로 변경하면 사용할 수 있습니다 items.parallelStream().anyMatch(inputStr::contains)
.
.filter(inputStr::contains).findAny()
일치하는 문자열을 반환하려는 경우 에도 사용할 수 있습니다 .
약간 날짜가 적힌 원래 답변 :
다음은 (VERY BASIC) 정적 메소드입니다. 비교 문자열에서는 대소 문자를 구분합니다. 원시적 그 사례를 구분을 할 방법은 전화를하는 것 toLowerCase()
또는 toUpperCase()
모두 입력 및 테스트 문자열을.
이보다 복잡한 작업을 수행해야하는 경우 Pattern and Matcher 클래스를 보고 정규 표현식을 수행하는 방법을 배우는 것이 좋습니다 . 일단 이해하면 해당 클래스 또는 String.matches()
도우미 메소드를 사용할 수 있습니다 .
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
답변
import org.apache.commons.lang.StringUtils;
사용하다:
StringUtils.indexOfAny(inputString, new String[]{item1, item2, item3})
찾은 문자열의 색인을 찾거나없는 경우 -1을 반환합니다.
답변
다음 과 같이 String # matches 메소드를 사용할 수 있습니다 .
System.out.printf("Matches - [%s]%n", string.matches("^.*?(item1|item2|item3).*$"));
답변
가장 쉬운 방법은 아마도 배열을 java.util.ArrayList로 변환하는 것입니다. 일단 배열 목록에 있으면 contains 메소드를 쉽게 활용할 수 있습니다.
public static boolean bagOfWords(String str)
{
String[] words = {"word1", "word2", "word3", "word4", "word5"};
return (Arrays.asList(words).contains(str));
}
답변
당신이 사용하는 경우 자바 8 위 또는, 당신은 신뢰할 수있는 스트림 API 와 같은 일을 :
public static boolean containsItemFromArray(String inputString, String[] items) {
// Convert the array of String items as a Stream
// For each element of the Stream call inputString.contains(element)
// If you have any match returns true, false otherwise
return Arrays.stream(items).anyMatch(inputString::contains);
}
String
테스트 할 큰 배열이 있다고 가정하면을 호출하여 검색을 병렬로 시작할 수도 parallel()
있습니다. 그러면 코드는 다음과 같습니다.
return Arrays.stream(items).parallel().anyMatch(inputString::contains);
답변
여기에 하나의 해결책이 있습니다.
public static boolean containsAny(String str, String[] words)
{
boolean bResult=false; // will be set, if any of the words are found
//String[] words = {"word1", "word2", "word3", "word4", "word5"};
List<String> list = Arrays.asList(words);
for (String word: list ) {
boolean bFound = str.contains(word);
if (bFound) {bResult=bFound; break;}
}
return bResult;
}
