get the first letter of each word in a string using objective-c

You could always use the method cStringUsingEncoding: and just iterate the const char*. Or better, you could use the method getCharacters:

When you iterate, you just have to do a for loop and check if the previous character is the ' ' character and append it to your temporary variable. If you want it uppercase, just use uppercaseString at the end.

see apple doc for more information: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/getCharacters:range:

I also struggle with strings sometime, the function names are not really similar to other languages like c++/java for instance.


Naïve solution:

NSMutableString * firstCharacters = [NSMutableString string];
NSArray * words = [@"this is my sentence" componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
for (NSString * word in words) {
  if ([word length] > 0) {
    NSString * firstLetter = [word substringToIndex:1];
    [firstCharacters appendString:[firstLetter uppercaseString]];
  }
}

Note that this is kinda stupid about breaking up words (just going by spaces, which isn't always the best approach), and it doesn't handle UTF16+ characters.

If you need to handle UTF16+ characters, change the if() statement inside the loop to:

if ([word length] > 0) {
  NSString * firstLetter = [word substringWithRange:[word rangeOfComposedCharacterSequenceAtIndex:0]];
  [firstCharacters appendString:[firstLetter uppercaseString]];
}

Tags:

Objective C