【问题标题】:How do I search an NSString sentence with words separated by commas for a specific word in iOS7?如何在 iOS7 中用逗号分隔单词的 NSString 句子中搜索特定单词?
【发布时间】:2014-05-09 20:48:11
【问题描述】:

我遇到了一个问题,其中有一个使用 rangeOfString 的示例。首先想到的是 NSPredicate。

我有不同的字符串返回由句子分隔的单词。例如,我有一个返回“男性,女性”。

搜索“男性”或“女性”的最有效方法是什么。如果单词恰好是句子的一部分,如果不是,我想执行一些操作。

NSDictionary,其中存储的单词用逗号分隔。我使用不同的键来抓取特定的单词。下面我使用返回“男性,女性”的“selectedGenders”键:

    if ([combinedRefinementSelection valueForKey:@"selectedGenders"]) {

        NSString *selectedGenders = [combinedRefinementSelection valueForKey:@"selectedGenders"];

        // Show string in label so customer knows how their clothes items will be filtered
        [[_thisController chosenGender] setText:selectedGenders];

    }

我只是想搜索 selectedGenders 并找出男性或女性是否是字符串的一部分。

【问题讨论】:

  • 您能发布一个数据示例吗?听起来像 CSV(逗号分隔值),但您的完整问题有点不清楚。

标签: ios objective-c cocoa-touch nsstring nspredicate


【解决方案1】:

正如你所说,rangeOfString 工作得很好。

NSString* sentence = @"Male, Female";

if ([sentence rangeOfString:@"Male"].location != NSNotFound)
{
   NSLog(@"Male is found");
}

if ([sentence rangeOfString:@"Female"].location != NSNotFound)
{
   NSLog(@"Female is found");
}

【讨论】:

  • 工作,很好,直截了当。
  • 当然,如果是@"female, female",那么搜索@"male"会返回true。
  • true 但搜索 @"Male" 不会;)
猜你喜欢
  • 1970-01-01
  • 2019-01-24
  • 1970-01-01
  • 2017-03-17
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
相关资源
最近更新 更多