I would like to change it to first name and last initial.
Thanks!
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 could be much more concise, but I wanted clarity for the OP :) Hence all the interim variables and var names.
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 whitespace, so you will need to check for that as well.
You can use this code snippet, first separate string using componentsSeparatedByString
, then join them again but only get the first character of Lastname
NSString *str = @"Firstname Lastname";
NSArray *arr = [str componentsSeparatedByString:@" "];
NSString *newString = [NSString stringWithFormat:@"%@ %@.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With