在循环中将字符串逐个字符转换为 NSMutableString
我正在尝试将字符串 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 char
s).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
for
循环超出了字符串的长度。数组是从零开始的,因此最后一个对象的索引为[gameWord length] - 1
。这应该有效:
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: