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);
An easy solution is using template literals and join().
To easily remove the last comma you can use the '\b' character. Save this answer.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With