Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

Example of what I am trying to do:

String = "This is my sentence"

I am looking to get this as a result: "TIMS"

I am struggling with objective-c and strings for some reason

like image 788
Slee Avatar asked Jul 15 '10 19:07

Slee


2 Answers

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]];
}
like image 99
Dave DeLong Avatar answered Nov 11 '22 18:11

Dave DeLong


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.

like image 30
Sauleil Avatar answered Nov 11 '22 17:11

Sauleil