从两个单词字符串中提取一个单词

时间:2013-10-06 19:39:07

标签: ios objective-c cocoa-touch

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

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

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

我研究了使用扫描仪的问题,并在这里找到了一个非常有用的答案: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 
    }

4 个答案:

答案 0 :(得分:5)

更好地使用NSString的{​​{1}}方法:

componentsSeparatedByString

答案 1 :(得分:3)

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

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

NSString *firstName = [terms objectAtIndex:0];

答案 2 :(得分:1)

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

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

答案 3 :(得分: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;
}];