在NSString中查找单词并在字符前后检查这个单词?

时间:2014-02-17 18:32:20

标签: ios objective-c nsstring

如何在NSString中查找单词并检查此单词前后的字符?

"This pattern has two parts separated by the"

如何找到tern以及如何检查

之前和之后的角色

在单词之前:"t" 单词后:" "

3 个答案:

答案 0 :(得分:3)

您可以使用 NSScanner 来获取这两个字符的索引。

示例:

NSString *string = @"tern";
NSScanner *scanner = [[NSScanner alloc] initWithString:@"This pattern has two parts separated by the"];

[scanner scanUpToString:string intoString:nil];

NSUInteger indexOfChar1 = scanner.scanLocation - 1;
NSUInteger indexOfChar2 = scanner.scanLocation + string.length;

您还可以使用 rangeOfString 方法:

示例:

NSRange range = [sourceString rangeOfString:stringToLookFor];
NSUInteger indexOfChar1 = range.location - 1;
NSUInteger indexOfChar2 = range.location +range.length + 1;

然后,当你有索引时,获取字符容易

NSString *firstCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar1, 1)];
NSString *secondCharacter = [sourceString substringWithRange:NSMakeRange(indexOfChar2, 1)];

希望这有帮助。

答案 1 :(得分:1)

以下是使用正则表达式的实现

NSString *testString= @"This pattern has two parts separated by the";
NSString *regexString = @"(.)(tern)(.)";

NSRegularExpression* exp = [NSRegularExpression 
  regularExpressionWithPattern:regexString 
  options:NSRegularExpressionSearch error:&error];

if (error) {
    NSLog(@"%@", error);
} else {
    NSTextCheckingResult* result = [exp firstMatchInString:testString options:0 range:NSMakeRange(0, [testString length] ) ];

if (result) {

NSRange groupOne = [result rangeAtIndex:1]; // 0 is the WHOLE string.
NSRange groupTwo = [result rangeAtIndex:2];
NSRange groupThree = [result rangeAtIndex:3];

NSLog(@"[%@][%@][%@]", 
     [testString substringWithRange:groupOne],
     [testString substringWithRange:groupTwo],
     [testString substringWithRange:groupThree] );
  }
}

结果:

[t][tern][ ]

答案 2 :(得分:0)

最好在NSString中获取pre和post字符,以避免处理unicode字符。

NSString * testString = @"This pattern has two parts separated by the";
NSString * preString;
NSString * postString;
NSUInteger maxRange;

NSRange range = [testString rangeOfString:@"tern"];


if(range.location == NSNotFound){
    NSLog(@"Not found");
    return;
}

if (range.location==0) {
    preString=nil;
}
else{
    preString = [testString substringWithRange:NSMakeRange(range.location-1,1)];
}

maxRange = NSMaxRange(range);

if ( maxRange >=testString.length ) {
    postString = nil;
}
else{
    postString = [testString substringWithRange:NSMakeRange(range.location+range.length, 1)];
}