iPhone - 将 NSString 拆分为 char NSString

发布于 2024-10-24 03:10:06 字数 659 浏览 3 评论 0原文

我有一个 {{"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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唐婉 2024-10-31 03:10:06

如果您想要字符串中的各个字符,请尝试 -characterAtIndex:。这将使您将它们作为 unichar 基元类型,然后您可以将其包装在 NSString 中,如下所示:

unichar ch = ...;
NSString *chString = [NSString stringWithCharacters: &ch length: 1];

为了保持唯一性,您可以将对象存储在 NSMutableSet< /code>,尽管它不会保留对象添加到其中的顺序。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文