ios - 합치기 - rangeofstring
Objective-C에 문자열에 다른 문자열이 포함되어 있는지 확인하려면 어떻게합니까? (14)
문자열 ( NSString
)에 다른 작은 문자열이 포함되어 있는지 어떻게 확인할 수 있습니까?
나는 다음과 같은 것을 기대하고 있었다.
NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
하지만 가장 가까운 곳은 다음과 같습니다.
if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
어쨌든, 문자열에 다른 문자열이 들어 있는지 찾는 가장 좋은 방법입니까?
Google에서이 결과가 상위 순위 인 것으로 보이므로 다음을 추가하고 싶습니다.
iOS 8 및 OS X 10.10에서는 containsString:
메서드를 NSString
추가합니다. 해당 시스템에 대한 Dave DeLong의 예제 업데이트 버전 :
NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
Oneliner (적은 양의 코드. DRY, NSLog
가 하나뿐입니다) :
NSString *string = @"hello bla bla";
NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla");
그래서 개인적으로 나는 정말로 NSNotFound
싫어하지만 그 필요성을 이해합니다.
그러나 일부 사람들은 NSNotFound와 비교하는 복잡성을 이해하지 못할 수도 있습니다.
예를 들어,이 코드는 다음과 같습니다.
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if([string rangeOfString:otherString].location != NSNotFound)
return YES;
else
return NO;
}
그 문제가있다 :
1) 분명히 otherString = nil
이면이 코드가 충돌합니다. 간단한 테스트는 다음과 같습니다.
NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
결과가 !! 크래시 !!
2) 객관적으로 새로운 사람에게는 그렇게 명확하지 않은 점은 string = nil
때 동일한 코드가 충돌하지 않는다는 것입니다. 예를 들어,이 코드는 다음과 같습니다.
NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
및이 코드 :
NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
둘 다
does string contains string - YES
분명히 당신이 원하는 것은 아닙니다.
그래서 내가 믿는 더 좋은 솔루션은 rangeOfString이 0의 길이를 반환한다는 사실을 사용하는 것이므로 더 신뢰할 수있는 코드는 다음과 같습니다.
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if(otherString && [string rangeOfString:otherString].length)
return YES;
else
return NO;
}
또는 간단하게 :
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
return (otherString && [string rangeOfString:otherString].length);
}
1과 2의 경우에 반환됩니다.
does string contains string - NO
그건 내 2 센트 ;-)
보다 유용한 코드를 보려면 내 Gist 를 확인하십시오.
다음은 복사하여 붙여 넣기 기능입니다.
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm
options:NSCaseInsensitiveSearch].location != NSNotFound;
}
문자열의 특정 위치가 필요할 경우이 코드는 Swift 3.0에 포함됩니다 .
let string = "This is my string"
let substring = "my"
let position = string.range(of: substring)?.lowerBound
스위프트 4 :
let a = "Hello, how are you?"
a.contains("Hello") //will return true
이 시도,
NSString *string = @"test Data";
if ([[string lowercaseString] rangeOfString:@"data"].location == NSNotFound)
{
NSLog(@"string does not contain Data");
}
else
{
NSLog(@"string contains data!");
}
이 코드를 사용하십시오.
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound)
{
NSLog(@"string does not contain bla");
}
else
{
NSLog(@"string contains bla!");
}
첫 번째 문자열에는 두 번째 문자열이 포함되거나 포함되지 않습니다.
NSString *first = @"Banana";
NSString *second = @"BananaMilk";
NSRange range = [first rangeOfString:second options:NSCaseInsensitiveSearch];
if (range.length > 0) {
NSLog(@"Detected");
}
else {
NSLog(@"Not detected");
}
최고의 솔루션. 이처럼 간단합니다! 단어 또는 문자열의 일부를 찾으려는 경우. 이 코드를 사용할 수 있습니다. 이 예에서는 단어의 값에 "acter"가 포함되어 있는지 확인합니다.
NSString *word [email protected]"find a word or character here";
if ([word containsString:@"acter"]){
NSLog(@"It contains acter");
} else {
NSLog (@"It does not contain acter");
}
참고 :이 답변은 현재 사용되지 않습니다.
NSString에 대한 카테고리 만들기 :
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
편집 : 다니엘 Galasko의 이름을 아래의 관찰에 관찰
SWift 4 이상
let str = "Hello iam midhun"
if str.contains("iam") {
//contain substring
}
else {
//doesn't contain substring
}
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
//categoryString does not contains Holiday
}
else
{
//categoryString contains Holiday
}
NSString *myString = @"hello bla bla";
NSRange rangeValue = [myString rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
if (rangeValue.length > 0)
{
NSLog(@"string contains hello");
}
else
{
NSLog(@"string does not contain hello!");
}
// 다음과 같이 사용할 수도 있습니다.
if (rangeValue.location == NSNotFound)
{
NSLog(@"string does not contain hello");
}
else
{
NSLog(@"string contains hello!");
}