2013-10-06 21 views
1

我已經在含有用戶的另一視圖控制器兩名字串定義的姓氏和名字從兩個詞串中提取一個字

NSString *userName = ([self hasAttributeWithName:kContractorName] ? [self attributeWithName:kContractorName].value : [self.certificate.contractor.name uppercaseString]); 

在另一個視圖控制器檢索該字符串時,我想只提取名字叫

我研究了SO使用掃描儀,發現了一個非常有用的答案在這裏:Objective C: How to extract part of a String (e.g. start with '#'),我幾乎在那裏。

問題是我只能看到提取第二個名字與我的原始代碼的變化。我掃描我的字符串到第一個和第二個名字之間的空間,這返回第二個名字罰款。剛纔需要有關如何設置此提取的第一個名字,而不是第二

NSMutableArray *substrings = [NSMutableArray new]; 
    NSScanner *scanner = [NSScanner scannerWithString:userName]; 
    [scanner scanUpToString:@" " intoString:nil]; // Scan all characters before 
    while(![scanner isAtEnd]) { 
     NSString *name = nil; 
     [scanner scanString:@" " intoString:nil]; // Scan the character 
     if([scanner scanUpToString:@" " intoString:&name]) { 
      // If the space immediately followed the , this will be skipped 
      [substrings addObject:name]; 
     } 
     [scanner scanUpToString:@" " intoString:nil]; // Scan all characters before next 
    } 
+0

您確定沒有名字可以包含空格字符嗎? –

回答

5

更好地利用NSStringcomponentsSeparatedByString方法:

NSString* firstName = [userName componentsSeparatedByString:@" "][0]; 
+0

謝謝,簡單而優雅的解決方案 – JSA986

1

你可以只拆分字符串轉換成使用componentsSeparatedByString姓和名的微調。

NSArray *subStrings = [userName componentsSeparatedByString:@" "]; 
NSString *firstName = [subStrings objectAtIndex:0]; 
3

如果第一個和最後一個名稱都用空格隔開,你可以使用:

NSArray *terms = [userName componentsSeparatedByString:@" "]; 

NSString *firstName = [terms objectAtIndex:0]; 
1

當然,你只能分割字符串由空格和第一個元素組成,但其中的樂趣在哪裏?嘗試NSLinguisticTagger實際上使用Cocoa API分割:

__block NSString *firstWord = nil; 

NSString *question = @"What is the weather in San Francisco?"; 
NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames; 
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:@"en"] options:options]; 
tagger.string = question; 

[tagger enumerateTagsInRange:NSMakeRange(0, [question length]) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:options usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) { 
    firstWord = [question substringWithRange:tokenRange]; 
    *stop = YES; 
}];