iPhone - 将 NSString 拆分为 char NSString
我有一个 {{"foo","仅食物"}, {"bar","babies are rad"} ... } 的 2d NSArray,我需要最终得到 2 个 NSArray:字符之一和对应的词之一。所以@“f”,@“o”,@“b”,@“a”,@“r”和@“食物”,@“仅”,@“婴儿”,@“是”,@“rad”将是我的两个 NSArray 的 NSStrings。
所以首先,我如何从 @"foo" 获取 @"f"、@"o"、@"o"
第二,我如何才能只保留唯一值?我猜测 NSDictionary 并且仅在 key 不存在时添加 @"f":@"food" @"o":@"only" 然后使用 getObjects:andKeys: 获取两个我将转换为的 C 数组NSArrays ..
根据下面的答案,我采用了以下内容。我实际上并没有使用 NSMutableDict,我只是在创建 2 个输出数组之前添加了我的字母以进行唯一性检查:
unichar ch = [[arr objectAtIndex:0] characterAtIndex:i];
NSString *s = [NSString stringWithCharacters: &ch length: 1];
if (![dict objectForKey:s]) {
}
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:andKeys: 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]) {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getCharacters 将帮助您开始使用字符数组: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html# //apple_ref/occ/instm/NSString/getCharacters:
您可以在之后循环并检查唯一性
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
如果您想要字符串中的各个字符,请尝试
-characterAtIndex:
。这将使您将它们作为unichar
基元类型,然后您可以将其包装在NSString
中,如下所示:为了保持唯一性,您可以将对象存储在
NSMutableSet< /code>,尽管它不会保留对象添加到其中的顺序。
If you want the individual characters of a string, try
-characterAtIndex:
. That will get you them as theunichar
primitive type, which you can then wrap inNSString
like so:To keep uniques, you can store objects in an
NSMutableSet
, though it will not preserve the order in which objects are added to it.