Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 958
user3281385 Avatar asked Feb 27 '14 21:02

user3281385


People also ask

How do you remove the last comma in a for loop?

An easy solution is using template literals and join().

How do you remove the last comma in CPP?

To easily remove the last comma you can use the '\b' character. Save this answer.

How to remove a comma at the end of a string in java?

We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string. length()-1 .


1 Answers

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);
like image 200
rmaddy Avatar answered Sep 30 '22 17:09

rmaddy