0

How do I concatenate the int length to the string I'm trying to slap into that array so it is "C10" given length == 10, of course. I see @"%d", intVarName way of doing it used else where. In Java I would of done "C" + length;. I am using the replaceObjectAtIndex method to replace the empty string, "", that I have previously populated the MSMutableArray "board" with. I am getting an error though when I add the @"C%d", length part at the end of that method (second to last line, above i++).

As part of my homework I have to randomly place "Chutes" (represented by a string of format, "C'length_of_chute'", in this first assignment they will always be of length 10 so it will simply be "C10") onto a game board represented by an array.

   -(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
    //??Make argument number of Chutes ??randomly?? across the board.
    for(int i = 0; i < length;){
        int random = arc4random_uniform(101);
        if ([[board objectAtIndex:random] isEqual:@""]) {
            //[board insertObject:@"C%d",length atIndex:random];
            [board replaceObjectAtIndex:random withObject:@"C%d",length];
            i++;
        }
    }
}

Please ignore the extra and junk code in there, I left it in for context.

1 Answer 1

1

In Objective-C the stringWithFormat method is used for formatting strings:

NSString *formattedString = [NSString stringWithFormat:@"C%d", length];
[someArray insertObject:formattedString];

It's often easier to create your formatted string on a line of its own in Objective-C, since as you can see the call can be fairly verbose!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I thought that having to format the string on it's own line might be the case.
You don't have to (you can nest the calls) - I would say doing so makes the code slightly less readable though. That's just my opinion, mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.