【问题标题】:checking if a string has specific words and fetching a word from sentence in objective C检查字符串是否包含特定单词并从目标 C 中的句子中获取单词
【发布时间】:2013-10-09 10:30:48
【问题描述】:

NSString *word = @"明天是星期一选择白车";

我想检查字符串是否有“select”和“car”然后我想得到汽车的颜色。在这里用户可以写“选择蓝色汽车”“选择红色汽车”,我只想在检查字符串是否有选择和汽车后获取颜色。 谢谢

【问题讨论】:

  • -1 表示不想阅读 NSString 的规范。

标签: iphone ios objective-c ipad nsstring


【解决方案1】:

只需检查单词@"select"是否在字符串中,如果是,则获取子字符串。

if([word rangeOfString:@"select"].location != NSNotFound){
  // Grab the next substring after the word @"select";
}

希望有帮助!

【讨论】:

  • 我还想确保它在字符串中也有 car。我想我可以检查 nsstring 中的两个字符串并取中间的子字符串。
  • 没错。您可以使用上面的代码来检查您喜欢的任何字符串!
  • 这不处理拼写错误或 select 是其他单词的子字符串的情况,例如选择的选择选择取消选择等。
  • 此外,英文中的颜色名称可以非常随意。您将需要一长串可能是颜色的单词。
  • 如果用户输入了一个非常不同的语法正确的句子怎么办?
【解决方案2】:

使用这个

if([string1 rangeOfString:@"select"].location != NSNotFound && [string1 rangeOfString:@"car"].location){

NSLog(@"select and car found");  

【讨论】:

  • 感谢您的回答,我做了同样的事情,但现在我必须制作一个颜色的子字符串。我试过这个 NSString *removeString= @"select"; NSRange 范围 = [值 rangeOfString:removeString]; NSInteger idx = range.location + range.length; NSString *szResult = [value substringFromIndex:idx];但这给了我选择后的所有单词,我只想在选择后获得下一个单词。
【解决方案3】:
NSString *word = @"Tomorrow is monday select white car";
if (([word rangeOfString:@"select"].location)&& ([word rangeOfString:@"car"].location)  != NSNotFound ) {
    NSLog(@"string contains select and car!");
} else {
    NSLog(@"string does not contain select and car!");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2011-05-20
    相关资源
    最近更新 更多