1

我在另一个视图控制器中有一个两个单词的字符串,其中包含用户定义的名字和姓氏

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

在另一个视图控制器中检索此字符串时,我只想提取名字。

我研究了关于使用扫描仪的问题,并在这里找到了一个非常有用的答案:Objective C: How to extract part of a String (eg 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 
    }
4

4 回答 4

5

更好的使用NSString'scomponentsSeparatedByString方法:

NSString* firstName = [userName componentsSeparatedByString:@" "][0];
于 2013-10-06T19:52:09.433 回答
3

如果名字和姓氏用空格分隔,您可以使用:

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

NSString *firstName = [terms objectAtIndex:0];
于 2013-10-06T19:52:36.377 回答
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;
}];
于 2013-10-06T20:07:06.387 回答
1

您可以使用 . 将字符串拆分为名字和姓氏componentsSeparatedByString

NSArray *subStrings = [userName componentsSeparatedByString:@" "];
NSString *firstName = [subStrings objectAtIndex:0];
于 2013-10-06T19:52:01.500 回答