在Objective-C或Swift中,如何通过搜索单词的一部分来获取单词?
例如:“我没有 w一切”
搜索键:“否”
结果:知道
要查找的任何方法吗?
答案 0 :(得分:4)
使用 Swift 2 ,我们可以使用“containsString”和“filter”:
let fullString = "I know everything"
let stringToFind = "no"
let wordsFound = fullString.componentsSeparatedByString(" ").filter { $0.containsString(stringToFind) }
print(wordsFound)
结果:
[ “知道”]
如果你给它一个包含多个匹配单词的句子,它会返回所有匹配项:
let fullString = "I know everything, nothing else"
结果:
[“知道”,“没有”]
与 Swift 3 相同:
let wordsFound = fullString.components(separatedBy: " ").filter { $0.contains(stringToFind) }
答案 1 :(得分:0)
NSString *fullString = @"I know everything";
NSString *stringToFind = @"no";
NSArray *components = [fullString componentsSeparatedByString:@" "];
for (NSString *word in components)
{
NSRange range = [word rangeOfString:stringToFind options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound)
{
NSLog(@"word we are looking for: %@", word);
}
else
{
NSLog(@"word %@ not contains substring", word);
}
}
答案 2 :(得分:0)
let testString = "I know everything, nothing else"
let testWord = "no"
var wordsContainingTestWord = [String]()
let words = testString.componentsSeparatedByString(" ")
for word in words {
if word.containsString(testWord) {
wordsContainingTestWord.append(word)
}
}
print(wordsContainingTestWord)
打印["知道","没有"]