ChrisWilson4
ChrisWilson4

Reputation: 195

Concatenating an int to a string in Objective-c

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.

Upvotes: 0

Views: 281

Answers (1)

lxt
lxt

Reputation: 31294

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!

Upvotes: 1

Related Questions