lab12
lab12

Reputation: 6448

Using strings and variables in the iPhone SDK

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.

Upvotes: 2

Views: 2122

Answers (2)

Tim
Tim

Reputation: 60130

Use NSString's stringByAppendingString: method:

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

Upvotes: 0

benzado
benzado

Reputation: 84338

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.

Upvotes: 5

Related Questions