我正在尝试编写一个函数,可以让我确定一个NSString*
是否包含另一个NSString*
的字符。例如,请参阅以下方案:
NSString *s1 = @"going";
NSString *s2 = @"ievngcogdl";
因此,当这两个字符串之间发生比较时,它应该返回true,因为第一个字符串s1
具有与第二个字符串s2
相同的字符。我可以使用NSCountedSet
吗?我知道这个类有一个方法containsObject:(id)
,虽然我认为这不会解决我的问题。有没有其他方法可以完成此功能并向我提供所需的结果?
答案 0 :(得分:2)
我认为这种方法可能相当慢,但我仍然赞成[NSString rangeOfCharacterFromSet:]
,这需要每次比较创建一个NSCharacterSet
对象:
- (BOOL)string:(NSString *)string containsAllCharactersInString:(NSString *)charString {
NSUInteger stringLen = [string length];
NSUInteger charStringLen = [charString length];
for (NSUInteger i = 0; i < charStringLen; i++) {
unichar c = [charString characterAtIndex:i];
BOOL found = NO;
for (NSUInteger j = 0; j < stringLen && !found; j++)
found = [string characterAtIndex:j] == c;
if (!found)
return NO;
}
return YES;
}
答案 1 :(得分:2)
这将有效 -
-(BOOL) string:(NSString *)string1 containsInputString:(NSString *)string2 {
// Build a set of characters in the string
NSCountedSet *string1Set = [[NSCountedSet alloc]init];
[string1 enumerateSubstringsInRange:NSMakeRange(0, string1.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[string1Set addObject:substring];
}];
// Now iterated over string 2, removing characters from the counted set as we go
for (int i=0;i<string2.length;i++) {
NSRange range = [string2 rangeOfComposedCharacterSequenceAtIndex:i];
NSString *substring = [string2 substringWithRange:range];
if ([string1Set countForObject:substring]> 0) {
[string1Set removeObject:substring];
}
else {
return NO;
}
}
return YES;
}
答案 2 :(得分:-1)
正则表达式是检查此类条件的最佳方式,并检查this link一次
下面我要为您的解决方案添加代码,请检查一次
NSString *s1 = @"going"
NSString *s2 = @"ievngcogdl";
if ([self string:s1 containsSameCharacterofString:s2]) {
NSLog(@"YES");
}
- (BOOL)string:(NSString *)str containsSameCharacterofString:(NSString *)charString
{
if (charString.length >= str.length) {
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:[NSString stringWithFormat:@"^[%@]+$", charString] options:NSRegularExpressionCaseInsensitive error:&error];
NSRange textRange = NSMakeRange(0, str.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:str options:NSMatchingReportProgress range:textRange];
return (matchRange.location != NSNotFound);
}
else {
return NO;
}
}
答案 3 :(得分:-3)
BOOL containsString = [@"Hello" containsString:@"llo"];
if (containsString) {
// Do Stuff
}