【发布时间】:2011-04-24 17:23:53
【问题描述】:
我想测试一个字符串,看看它是否包含文本“hello”。我希望测试不考虑大写。如何测试这个字符串?
【问题讨论】:
标签: iphone xcode nsstring string-comparison text-comparison
我想测试一个字符串,看看它是否包含文本“hello”。我希望测试不考虑大写。如何测试这个字符串?
【问题讨论】:
标签: iphone xcode nsstring string-comparison text-comparison
使用下面的代码作为参考查找子字符串到字符串中的检查。
NSString* string = @"How to test a string for text" ;
NSString* substring = @"string for" ;
NSRange textRange;
textRange =[string rangeOfString:substring options:NSCaseInsensitiveSearch];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}
【讨论】:
【讨论】:
NSRange range = [string rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
BOOL notFound = range.location==NSNotFound;
【讨论】:
我假设所有单词都用空格分隔,并且没有标点符号。如果有标点符号。
NSArray *dataArray = [inputString componentsSeparatedByString:@" "];
for(int i=0; i<[dataArray count]){
if([[dataArray objectAtIndex:i] isEqualToString:@"hello"]){
NSLog(@"hello has been found!!!");
}
}
我没有对此进行测试,但理论上它应该可以工作。
查看文档以了解删除标点符号并使字符串全部小写的方法。这应该很简单。
【讨论】:
这里的其他解决方案很好,但你真的应该使用正则表达式,
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(hello)*$"
options:NSRegularExpressionCaseInsensitive
error:&error];
【讨论】:
NSRegularExpression 得到NSString 的内置搜索不能以更少的数量级执行?