views:

791

answers:

2

Hey guys,

I have this quick problem I need to solve. I have a string here like so:

textbox.text =@"Your name is"

then I want to add right after "your name is" a variable that displays text.

so in Visual Basic I learned it like this...

textbox.text =@"Your name is" & variable1.

but now i can see that it doesn't work like that in cocoa.

Please help me solve this...

+5  A: 
textbox.text = [NSString stringWithFormat:@"Your name is %@", variable1];

Read the documentation for stringWithFormat: to learn about string format specifiers. Basically, you have a format string that contains codes like %@, and the following arguments are put in place of those escape codes.

It has the same syntax as the old C-style printf() function. Cocoa's logging function, NSLog(), also works the same way.

If you need to combine a lot of strings together, try also reading about NSMutableString.

You could also do:

textbox.text = [@"Your name is " stringByAppendingString:variable1];

But if you have to concatenate more than two things, stringWithFormat: is much more concise.

benzado
A: 

Use NSString's stringByAppendingString: method:

textbox.text = [@"Your name is" stringByAppendingString:variable1];
Tim