在NSString中包含变量? [英] Include a variable inside a NSString?

查看:80
本文介绍了在NSString中包含变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很好,我们都知道:

NSString *textoutput = @"Hello";
outLabel.text = textoutput;

但是,如果要在该NSString语句中包含一个变量,如下所示:

However, what if you want to include a variable inside that NSString statement like the following:

NSString *textoutput =@"Hello" Variable;

在C ++中,我知道我什么时候cout,并且想要包含一个变量,我所做的只是这样:

In C++ I know when I cout something and I wanted to include a variable all I did was soemthing like this:

cout << "Hello" << variableName << endl;

因此,我正在尝试使用Objective-C完成此操作,但我不知道如何实现.

So I'm trying to accomplish that with Objective-C but I don't see how.

推荐答案

您可以使用以下功能进行一些精美的格式设置:

You can do some fancy formatting using the following function:

NSString *textoutput = [NSString stringWithFormat:@"Hello %@", variable];

请注意,%@假定variable是Objective-C对象.如果它是C字符串,请使用%s,如果它是任何其他C类型,请查看printf参考.

Note that %@ assumes that variable is an Objective-C object. If it's a C string, use %s, and if it's any other C type, check out the printf reference.

或者,您可以通过将字符串追加到现有字符串来创建新字符串:

Alternatively, you can create a new string by appending a string to an existing string:

NSString *hello = @"Hello";
NSString *whatever = [hello stringByAppendingString:@", world!"];

请注意,NSString是不可变的-一旦分配了值,就无法更改它,只能派生新对象.如果要在字符串后面添加很多内容,则应该改用NSMutableString.

Note that NSString is immutable -- once you assign a value, you can't change it, only derive new objects. If you are going to be appending a lot to a string, you should probably use NSMutableString instead.

这篇关于在NSString中包含变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆