ghiboz
ghiboz

Reputation: 8003

iphone string initial char before space

I have a question... I wish take from a string that contains a name and surname, the initial of the first and the surname complete.... example:

NSString* myName = @"Mel Gibson";
//I Wish have "M Gibson";

NSString* myName2 = @"Leonardo Di Caprio";
//I wish have "L Di Caprio";

Thanks

Upvotes: 1

Views: 360

Answers (1)

kennytm
kennytm

Reputation: 523334

@implementation NSString (AbbreviateFirstWord)
-(NSString*)stringByAbbreviatingFirstWord {
   // step 1: Locate the white space.
   NSRange whiteSpaceLoc = [self rangeOfString:@" "];
   if (whiteSpaceLoc.location == NSNotFound)
     return self;
   // step 2: Remove all characters between the first letter and the white space.
   NSRange rangeToRemove = NSMakeRange(1, whiteSpaceLoc.location - 1);
   return [self stringByReplacingCharactersInRange:rangeToRemove withString:@""];
}
@end

Upvotes: 6

Related Questions