iPhone - Splitting an NSString into char NSStrings
I've got a 2d NSArray of {{"foo","food only only"}, {"bar","babies are rad"} ... } and I need to end up with 2 NSArrays: one of characters and one of the corresponding words. So @"f", @"o",@"b",@"a",@"r" and @"food",@"only",@"babies",@"are",@"rad" would be my two NSArray's of NSStrings.
So first, how do I get @"f",@"o",@"o" from @"foo"
And second how can I only keep the uniques? I'm guessing NSDictionary and only add if key is not there giving me @"f":@"food" @"o":@"only" then use getObjects:andKey开发者_StackOverflows: to get two C arrays which I'll convert to NSArrays..
Based on the below answer I went with the following. I didn't actually use the NSMutableDict, I just added my letters to it to get the uniqueness check before creating my 2 output arrays:
unichar ch = [[arr objectAtIndex:0] characterAtIndex:i];
NSString *s = [NSString stringWithCharacters: &ch length: 1];
if (![dict objectForKey:s]) {
}
getCharacters will get you started with an array of characters: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/getCharacters:
You could cycle through and check for uniques after
If you want the individual characters of a string, try -characterAtIndex:
. That will get you them as the unichar
primitive type, which you can then wrap in NSString
like so:
unichar ch = ...;
NSString *chString = [NSString stringWithCharacters: &ch length: 1];
To keep uniques, you can store objects in an NSMutableSet
, though it will not preserve the order in which objects are added to it.
精彩评论