문자열에 어레이의 문자열이 포함되어 있는지 테스트합니다.
어레이의 문자열이 포함되어 있는지 확인하기 위해 문자열을 테스트하려면 어떻게 해야 합니까?
사용하는 대신
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).anyMatch(inputStr::contains);
}
또한 입력 유형을 배열이 아닌 목록으로 변경하면 사용할 수 있습니다.items.stream().anyMatch(inputStr::contains)
.
를 사용할 수도 있습니다..filter(inputStr::contains).findAny()
일치하는 문자열을 반환하는 경우.
중요: 위의 코드는 다음을 사용하여 수행할 수 있습니다.parallelStream()
대부분의 경우 퍼포먼스에 방해가 됩니다.병렬 스트리밍에 대한 자세한 내용은 이 질문을 참조하십시오.
약간 날짜가 지난 답변 원본:
(VERY BASIC) 스태틱 방식을 다음에 나타냅니다.비교 문자열에서는 대소문자를 구분합니다.상황을 둔감하게 만드는 가장 기본적인 방법은toLowerCase()
또는toUpperCase()
입력 스트링과 테스트스트링 양쪽에 있습니다.
이것보다 더 복잡한 것을 해야 한다면 패턴과 매처 클래스를 보고 정규 표현을 배우는 것을 추천합니다.그런 것들을 이해하면 그 수업이나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 8 이상을 사용하는 경우 Stream 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
를 호출하여 검색을 병렬로 시작할 수도 있습니다.이 때 코드는 다음과 같습니다.
return Arrays.stream(items).parallel().anyMatch(inputString::contains);
가장 쉬운 방법은 어레이를 java.util로 변환하는 것입니다.어레이 리스트배열 목록에 있으면 contains 메서드를 쉽게 활용할 수 있습니다.
public static boolean bagOfWords(String str)
{
String[] words = {"word1", "word2", "word3", "word4", "word5"};
return (Arrays.asList(words).contains(str));
}
다음은 한 가지 해결 방법입니다.
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의 구현 이후,어떤 방법이든.
이것을 시험해 보세요.
if (Arrays.stream(new String[] {item1, item2, item3}).anyMatch(inputStr::contains))
보다 groovyesque한 접근방식은 inject를 metaClass와 조합하여 사용하는 것입니다.
꼭 말씀드리고 싶습니다.
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 변수에 대해 존재하는 Any는 오브젝트 대신 메서드를 클래스에 추가합니다.
String.metaClass.containsAny={notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
다음과 같이 할 수도 있습니다.
if (string.matches("^.*?((?i)item1|item2|item3).*$"))
(?i): used for case insensitive
.*? & .*$: used for checking whether it is present anywhere in between the string.
단어 전체를 검색할 경우 대소문자를 구분하지 않는 이 작업을 수행할 수 있습니다.
private boolean containsKeyword(String line, String[] keywords)
{
String[] inputWords = line.split(" ");
for (String inputWord : inputWords)
{
for (String keyword : keywords)
{
if (inputWord.equalsIgnoreCase(keyword))
{
return true;
}
}
}
return false;
}
대소문자를 구분하지 않는 일치를 찾고 있는 경우는, 패턴을 사용해 주세요.
Pattern pattern = Pattern.compile("\\bitem1 |item2\\b",java.util.regex.Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
...
}
코틀린에서
if (arrayOf("one", "two", "three").find { "onetw".contains(it) } != null){
doStuff()
}
Strings가 검색 중인 어레이라고 가정하면 다음과 같습니다.
Arrays.binarySearch(Strings,"mykeytosearch",mysearchComparator);
여기서 mykeytosearch는 배열 내의 존재 여부를 테스트하는 문자열입니다.mysearch Comparator는 문자열을 비교하는 데 사용되는 비교 도구입니다.
자세한 내용은 Arrays.binary Search를 참조하십시오.
if (Arrays.asList(array).contains(string))
언급URL : https://stackoverflow.com/questions/8992100/test-if-a-string-contains-any-of-the-strings-from-an-array
'programing' 카테고리의 다른 글
Vue Router가 항상 브라우저를 새로고침 - vuex-state 손실 (0) | 2022.05.31 |
---|---|
v-for에서 v-if에 대한 VueJS 필터 (0) | 2022.05.31 |
Vue.js: 단순 클릭 기능이 실행되지 않음 (0) | 2022.05.30 |
Axios를 사용하여 이미지를 서버에 업로드하려면 어떻게 해야 합니까? (0) | 2022.05.30 |
Vue에서 선택한 옵션을 조건부로 설정하는 방법 (0) | 2022.05.30 |