문자열에 배열의 문자열이 포함되어 있는지 테스트
배열의 문자열이 포함되어 있는지 확인하려면 문자열을 어떻게 테스트합니까?
사용하는 대신
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);
이 시도:
if (Arrays.asList(item1, item2, item3).contains(string))
여기에 하나의 해결책이 있습니다.
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;
}
버전 3.4부터 Apache Common Lang 3은 containsAny 메소드를 구현합니다 .
더 groovyesque 접근 방식은 metaClass 와 함께 inject 를 사용 하는 것입니다 .
나는 말하고 싶습니다 :
String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true
그리고 방법은 다음과 같습니다.
myInput.metaClass.containsAny={List<String> notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
향후 String 변수에 대해 containsAny 가 필요 하면 객체 대신 클래스에 메소드를 추가하십시오.
String.metaClass.containsAny={notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
대소 문자를 구분하지 않으면 패턴을 사용하십시오.
Pattern pattern = Pattern.compile("\\bitem1 |item2\\b",java.util.regex.Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if(matcher.find() ){
}
if (Arrays.asList(array).contains(string))
Strings 가 검색하는 배열 이라고 가정하면 아래에서 작동합니다 .
Arrays.binarySearch(Strings,"mykeytosearch",mysearchComparator);
where mykeytosearch is the string that you want to test for existence within the array. mysearchComparator - is a comparator that would be used to compare strings.
Refer to Arrays.binarySearch for more information.
'Programing' 카테고리의 다른 글
코드의 "복사 및 붙여 넣기"가 위험한 이유는 무엇입니까? (0) | 2020.07.02 |
---|---|
왜이 C ++ 스 니펫 컴파일 (비 공백 함수가 값을 반환하지 않음) (0) | 2020.07.02 |
@ManyToOne 속성에는 @Column이 허용되지 않습니다. (0) | 2020.07.02 |
페이스 북 데이터베이스 디자인? (0) | 2020.07.02 |
롬복은 어떻게 작동합니까? (0) | 2020.07.02 |