Objective-C:在循环中从 NSString 中删除尾随逗号

标签 objective-c for-loop nsstring

这是我的入门级 Objc 类(class)中的一个简单挑战,它让我很伤心。我已经尝试了一些我在 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);

最佳答案

更好的方法是这样的:

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);

关于Objective-C:在循环中从 NSString 中删除尾随逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22080444/

相关文章:

objective-c - FinderSync 上下文菜单在错误的类中调用操作

css - 在 SASS 中创建一个集合(数组)用于@for 循环

c - 如何让 C 查看文件并找到某个字符串?

ios - 为从字符串文字分配的 NSStrings 获取相同的内存地址

ios - 在 GetCell 方法中删除动态单元格

ios - 如何在ios中将当前位置用户头像居中

objective-c - encodeHexString objc 实现,我是否应该支持奇数长度的十六进制字符串,如果是,如何?

iphone - iPhone 如何将 double 类型转换为 string 类型?

iPhone MKMapView : Detecting Nearest Locations in Array from Current Location

python - 需要澄清我在 Python 中的 for 循环逻辑