2010-04-06 39 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

相關問題