2010-04-06 77 views
0

假设我可以有以下字符串:如何检测某些字符是否在NSString的末尾?

"hey @john..." 
"@john, hello" 
"@john(hello)" 

我令牌化的字符串让每一个字用空格分隔:

[myString componentsSeparatedByString:@" "]; 

我的令牌数组现在包含:

@john... 
@john, 
@john(hello) 

我正在检查标点符号如下:

NSRange textRange = [words rangeOfString:@","]; 
if(textRange.location != NSNotFound){ } //do something 

对于这些情况。我怎样才能确保只有@约翰标记化,同时保留了尾部字符:

... 
, 
(hello) 

注:我想是能够处理字符的所有情况下,一个字符串的结尾。以上只是3个例子。

回答

1

查看NSString的-rangeOfString:options:range: ...给它一个范围{ [myString length] - [searchString length], [searchString length] },看看结果范围的位置是否等于NSNotFound。请参阅文档中的NSStringCompareOptions选项以区分大小写等。

0

您可以使用NSScannerNSCharacterSet来执行此操作。 NSScanner可以扫描一个字符串,直到集合中第一个字符出现为止。如果你得到+alphaNumericCharacterSet,然后打电话给-invertedSet,你会得到一组所有非字母数字字符。

这可能不是超高效,但它的工作:

NSArray* strings = [NSArray arrayWithObjects: 
        @"hey @john...", 
        @"@john, hello", 
        @"@john(hello)", 
        nil]; 

//get the characters we want to skip, which is everything except letters and numbers 
NSCharacterSet* illegalChars = [[NSCharacterSet alphanumericCharacterSet] invertedSet]; 


for(NSString* currentString in strings) 
{ 
    //this stores the tokens for the current string 
    NSMutableArray* tokens = [NSMutableArray array]; 

    //split the string into unparsed tokens 
    NSArray* split = [currentString componentsSeparatedByString:@" "]; 

    for(NSString* currentToken in split) 
    { 
     //we only want tokens that start with an @ symbol 
     if([currentToken hasPrefix:@"@"]) 
     { 
      NSString* token = nil; 

      //start a scanner from the first character after the @ symbol 
      NSScanner* scanner = [NSScanner scannerWithString:[currentToken substringFromIndex:1]]; 
      //keep scanning until we hit an illegal character 
      [scanner scanUpToCharactersFromSet:illegalChars intoString:&token]; 

      //get the rest of the string 
      NSString* suffix = [currentToken substringFromIndex:[scanner scanLocation] + 1]; 

      if(token) 
      { 
       //store the token in a dictionary 
       NSDictionary* tokenDict = [NSDictionary dictionaryWithObjectsAndKeys: 
              [@"@" stringByAppendingString:token], @"token", //prepend the @ symbol that we skipped 
              suffix, @"suffix", 
              nil]; 
       [tokens addObject:tokenDict]; 
      } 
     } 
    } 
    //output 
    for(NSDictionary* dict in tokens) 
    { 
     NSLog(@"Found token: %@ additional characters: %@",[dict objectForKey:@"token"],[dict objectForKey:@"suffix"]); 
    } 
} 
+0

不错的解决方案。虽然这可行,并且可以检测字符串中的非字母数字,但我仍然需要能够在稍后保留用户的字母数字字符。 – 2010-04-07 01:53:23

+0

我修改了这个例子来存储额外的字符。 – 2010-04-07 02:46:17

相关问题