开发者

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 th开发者_StackOverflowat it doesn't work like that in Cocoa.


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.


Use NSString's stringByAppendingString: method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜