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
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]];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With