Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a NSString like this: "Firstname Lastname". How do I convert it to "Firstname L."?

Tags:

ios

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

Thanks!

like image 876
dot Avatar asked Jul 03 '12 22:07

dot


3 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 could be much more concise, but I wanted clarity for the OP :) Hence all the interim variables and var names.

like image 115
WendiKidd Avatar answered Oct 20 '22 22:10

WendiKidd


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.

like image 40
Anton Avatar answered Oct 21 '22 00:10

Anton


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]];
like image 2
Omar Abdelhafith Avatar answered Oct 20 '22 22:10

Omar Abdelhafith