【问题标题】:How can I learn if 2 NSStrings are almost same to eachother?我如何知道 2 个字符串是否彼此几乎相同?
【发布时间】:2013-03-04 14:01:55
【问题描述】:

我从用户那里获取了一个字符串,并对其进行了一些迭代。

例如用户输入文字@“今天天气真好。”;

当用户输入 "the wether is beatifullll tdy""th weather is beatttiful tooodayy""the weatherrr iss beautiful toda" 时,我想进行相同的迭代。

这是我的代码:

// (str is the user's text)

if ([str rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location != NSNotFound) {
// when user entered helloo I want make to same iteration,
// but in this case the program goes else part.        
    [array insertObject:@"hello" atIndex:s];
} else if ([str rangeOfString:@"You are so beautiful" options:NSCaseInsensitiveSearch].location != NSNotFound ) {
    [dizi insertObject:@"I know, Thanks" atIndex:s];
} else if ([str rangeOfString:@"Have Lunch?" options:NSCaseInsensitiveSearch].location != NSNotFound) {
    [array insertObject:@"Yes,I have" atIndex:s];
} else {
    [array insertObject:@"please,speak english" atIndex:s];
}

【问题讨论】:

  • 那么你的问题是什么?
  • 听起来你想做模糊匹配...
  • 他有 2 个字符串,想知道它们的匹配程度——它们有多接近——霍夫曼距离可以工作
  • @trojanfoe 这就是我要找的词:D
  • 是的,你使用模糊匹配。

标签: xcode nsstring compare


【解决方案1】:

您可以使用 StringScore 进行模糊匹配:

https://github.com/thetron/StringScore

例子:

NSString *testString = @"Hello world!";

CGFloat result1 = [testString scoreAgainst:@"Hello world!"];
CGFloat result2 = [testString scoreAgainst:@"world"];
CGFloat result3 = [testString scoreAgainst:@"wXrld" fuzziness:[NSNumber numberWithFloat:0.8]];
CGFloat result4 = [testString scoreAgainst:@"world" fuzziness:nil options:NSStringScoreOptionFavorSmallerWords];
CGFloat result5 = [testString scoreAgainst:@"world" fuzziness:nil options:(NSStringScoreOptionFavorSmallerWords & NSStringScoreOptionReducedLongStringPenalty)];
CGFloat result6 = [testString scoreAgainst:@"HW"]; // abbreviation matching example

NSLog(@"Result 1 = %f", result1);
NSLog(@"Result 2 = %f", result2);
NSLog(@"Result 3 = %f", result3);
NSLog(@"Result 4 = %f", result4);
NSLog(@"Result 5 = %f", result5);
NSLog(@"Result 6 = %f", result6);

输出:

Result 1 = 1.000000
Result 2 = 0.425000
Result 3 = 0.271528
Result 4 = 0.250000
Result 5 = 0.425000
Result 6 = 0.645833

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 2018-03-31
    • 2020-10-05
    • 1970-01-01
    • 2011-01-18
    • 2020-09-16
    • 2018-06-07
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多