【问题标题】:How to test a string for text如何测试字符串的文本
【发布时间】:2011-04-24 17:23:53
【问题描述】:

我想测试一个字符串,看看它是否包含文本“hello”。我希望测试不考虑大写。如何测试这个字符串?

【问题讨论】:

    标签: iphone xcode nsstring string-comparison text-comparison


    【解决方案1】:

    使用下面的代码作为参考查找子字符串到字符串中的检查。

        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
        }
    

    【讨论】:

      【解决方案2】:

      【讨论】:

        【解决方案3】:
        NSRange range = [string rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
        BOOL notFound = range.location==NSNotFound;
        

        【讨论】:

          【解决方案4】:

          我假设所有单词都用空格分隔,并且没有标点符号。如果有标点符号。

          NSArray *dataArray = [inputString componentsSeparatedByString:@" "];

          for(int i=0; i<[dataArray count]){
           if([[dataArray objectAtIndex:i] isEqualToString:@"hello"]){
              NSLog(@"hello has been found!!!");
           } 
          }
          

          我没有对此进行测试,但理论上它应该可以工作。

          查看文档以了解删除标点符号并使字符串全部小写的方法。这应该很简单。

          【讨论】:

          • 按照格雷厄姆·李的说法。更有意义,没有意识到这个功能的存在。
          【解决方案5】:

          这里的其他解决方案很好,但你真的应该使用正则表达式,

          NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(hello)*$"
                                                                             options:NSRegularExpressionCaseInsensitive
                                                                               error:&error];
          

          文档在这里:http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

          【讨论】:

          • 两件事:首先你的正则表达式不满足提问者的要求;其次为什么应该使用正则表达式“真的”?因为 perl 很酷?我不反对,但没有正当理由这样的说法是毫无价值的。
          • 来吧,别讽刺了。任何类型的匹配都应该使用正则表达式完成。正则表达式与语言无关。
          • @sciritai 但是为什么?什么使用NSRegularExpression 得到NSString 的内置搜索不能以更少的数量级执行?
          • 对所有你喜欢的关于更少的行进行竖琴,这是一个很好的做法。我的建议是有效的。
          • 让我换一种说法。 为什么? 你说“你真的应该使用正则表达式”,我只是想知道为什么这样做更好。到目前为止,您还无法提供理由。如果在这种情况下使用正则表达式更好,我很想听听,因为我从 WebObjects 4.5 开始就毫无问题地使用了 NSString 的字符串搜索 API。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-21
          • 1970-01-01
          • 2015-04-27
          相关资源
          最近更新 更多