views:

22

answers:

1

Hi all! 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

+6  A: 
@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
KennyTM
Good job! Was just posting answer myself, when it said there were new ones. This is a lot better than what I was posting, and for that I give you +1 ;)
jrtc27
thanks and I need to paste this code into my class and to use?
ghiboz
@ghi: Just put it in any `.m` file. Remember to include the `@interface` for this [category](http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/objectivec/Articles/ocCategories.html) in an `.h` file though.
KennyTM
thanks Kenny!!!!
ghiboz