I have NSString: "First Name Last Name". How to convert it to "Firstname L."?

I would like to change it to first and last name.

Thank!

+5
source share
4 answers
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];

This may be much more concise, but I need clarity for the OP :) Therefore, all temporary variables and variable names.

+13
source

This would do it:

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 spaces, so you will need to check this as well.

+4
source

, , componentsSeparatedByString, , Lastname

NSString *str = @"Firstname Lastname";
NSArray *arr = [str componentsSeparatedByString:@" "];
NSString *newString = [NSString stringWithFormat:@"%@ %@.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]];
+2

:

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

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

, :

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

This will skip any middle names, although if there is only one name, for example "Jeffry", it will output "Jeffry J.". If you go to an empty string, this will throw an exception when trying to get objectAtIndex:0, since this array will be empty. Therefore you should check [nameComponents count].

0
source

All Articles