:
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].
Tommy source
share