use*_*385 6 for-loop objective-c nsstring
在我的介绍性Objc课程中,这是一个简单的挑战,这让我感到非常悲痛.我已经尝试了一些我在X-code API中选择的东西试图解决这个问题,但我没有运气.挑战规范包括限制:我不能更改for循环之外的任何代码,我的输出不能包含尾随逗号.它目前的迭代确实如此,我不知道如何摆脱它!
以下是当前形式的代码:
NSString *outputString = @"";
int loopMaximum = 10;
for (int counter = 1; counter <= loopMaximum; counter++) {
outputString = [NSString stringWithFormat:@"%@ %d,", outputString, counter];
//Not sure how to get rid of trailing comma =/
}
NSLog(@"%@", outputString);
Run Code Online (Sandbox Code Playgroud)
更好的方法是这样的:
NSMutableString *outputString = [NSMutableString string];
int loopMaximum = 10;
for (int counter = 1; counter <= loopMaximum; counter++) {
if (counter > 1) {
[outputString appendString:@", "];
}
[outputString appendFormat:@"%d", counter];
}
NSLog(@"%@", outputString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
618 次 |
| 最近记录: |