在循环中将字符串逐个字符转换为 NSMutableString

发布于 2024-12-11 07:14:35 字数 860 浏览 0 评论 0原文

我正在尝试将字符串 gameWord 的每个单独字符放入 NSMutableArray 中。 我将每个 char 转换为一个对象,然后使用以下代码将对象添加到 NSMutableArray 中:

NSMutableString *letterOne = [[NSMutableString alloc] initWithFormat:@"%C",[gameWord characterAtIndex:0]];

NSMutableString *letterTwo = [[NSMutableString alloc] initWithFormat:@"%C",[gameWord characterAtIndex:1]];

依此类推......

我不明白的是为什么下面的循环不起作用?

NSMutableArray *lettersArray = [[NSMutableArray alloc] initWithCapacity:[gameWord length]];

for (int x = 0 ; x <= [gameWord length] ; x++) {

    NSMutableString *letter = [[NSMutableString alloc]initWithFormat:@"%C",[gameWord characterAtIndex:x]];

       [lettersArray addObject:letter];
       [letter release];
    }

非常感谢您帮助理解这个问题以及将 NSString 的每个字符放入单个对象(而不是 char)的任何其他方法。

I'm trying to get each individual character of a string, gameWord, into an NSMutableArray.
I'm converting each char into an object and then adding the objects into the NSMutableArray with the following code:

NSMutableString *letterOne = [[NSMutableString alloc] initWithFormat:@"%C",[gameWord characterAtIndex:0]];

NSMutableString *letterTwo = [[NSMutableString alloc] initWithFormat:@"%C",[gameWord characterAtIndex:1]];

and so on....

What I don't understand is why the following loop won't work?

NSMutableArray *lettersArray = [[NSMutableArray alloc] initWithCapacity:[gameWord length]];

for (int x = 0 ; x <= [gameWord length] ; x++) {

    NSMutableString *letter = [[NSMutableString alloc]initWithFormat:@"%C",[gameWord characterAtIndex:x]];

       [lettersArray addObject:letter];
       [letter release];
    }

Would really appreciate help understanding this problem and any other ways of getting each character of an NSString into individual objects (not chars).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

·深蓝 2024-12-18 07:14:35

您的 for 循环超出了字符串的长度。数组是从零开始的,因此最后一个对象的索引为[gameWord length] - 1

这应该有效:

for (int x = 0; x < [gameWord length]; x++) {
    //...         ^--changed from <= to <
}

Your for loop goes beyond the length of the string. Arrays are zero-based, so the last object has the index [gameWord length] - 1.

This should work:

for (int x = 0; x < [gameWord length]; x++) {
    //...         ^--changed from <= to <
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文