Objective-C: Removing trailing comma from NSString in a loop

for-loop, nsstring, objective-c

Solution

The better approach is something like this:

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

Problem

This is a simple challenge in my introductory Objc class that is causing my a lot of grief. I've tried a few things I picked up in the X-code API to try to fix this but I'm having no luck. The challenge specifications include a restriction: I cannot change any code outside the for loop and my output cannot include a trailing comma. In its current iteration it does, and I don't know how to get rid of it! Here is the code in its current form: ``` 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); ```

Original source

Related problems