5

我想将其更改为名字和姓氏首字母。

谢谢!

4

4 回答 4

14
NSString* nameStr = @"Firstname Lastname";
NSArray* firstLastStrings = [nameStr componentsSeparatedByString:@" "];
NSString* firstName = [firstLastStrings objectAtIndex:0];
NSString* lastName = [firstLastStrings objectAtIndex:1];
char lastInitialChar = [lastName characterAtIndex:0];
NSString* newNameStr = [NSString stringWithFormat:@"%@ %c.", firstName, lastInitialChar];

这可能更简洁,但我希望 OP 更清晰 :) 因此所有的临时变量和 var 名称。

于 2012-07-03T22:25:01.060 回答
4

这会做到:

NSArray *components = [fullname componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstnameAndLastnameInitial = [NSString stringWithFormat:@"%@ %@.", [components objectAtIndex:0], [[components objectAtIndex:1] substringToIndex:1]];

This assumes that fullname is an instance of NSString and contains two components separated by whitespace, so you will need to check for that as well.

于 2012-07-03T22:27:01.083 回答
2

您可以使用此代码片段,首先使用 分隔字符串componentsSeparatedByString,然后再次加入它们,但只能获取第一个字符Lastname

NSString *str = @"Firstname Lastname";
NSArray *arr = [str componentsSeparatedByString:@" "];
NSString *newString = [NSString stringWithFormat:@"%@ %@.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]];
于 2012-07-03T22:24:58.780 回答
0

分别获取名称各部分的数组:

NSString *sourceName = ...whatever...;

NSArray *nameComponents =
    [sourceName
        componentsSeparatedByCharactersInSet:
            [NSCharacterSet whitespaceCharacterSet]];

然后,我猜:

NSString *compactName =
    [NSString stringWithFormat:@"%@ %@.",
        [nameComponents objectAtIndex:0],
        [[nameComponents lastObject] substringToIndex:1]];

这将跳过任何中间名,但如果只有一个名字,比如说“Jeffry”,那么它将输出“Jeffry J.”。如果您传入空字符串,那么当您尝试获取时它将引发异常,objectAtIndex:0因为该数组将为空。所以你应该检查一下[nameComponents count]

于 2012-07-03T22:25:11.317 回答