ios developer tiny share-20161013

本文介绍了Objective-C中如何使用NSString和NSMutableString类来创建和操作字符串。详细解释了字符串的创建方式,包括初始化、格式化字符串等,并展示了如何通过NSMutableString进行字符串内容的实时修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天讲Objective-C的基本类型对应的对象封装类型


Objects Can Represent Primitive Values

If you need to represent a scalar value as an object, such as when working with the collection classes described in the next section, you can use one of the basic value classes provided by Cocoa and Cocoa Touch.

Strings Are Represented by Instances of the NSString Class
As you’ve seen in the previous chapters, NSString is used to represent a string of characters, like Hello World. There are various ways to create NSString objects, including standard allocation and initialization, class factory methods or literal syntax:

NSString *firstString = [[NSString alloc] initWithCString:"Hello World!"
												 encoding:NSUTF8StringEncoding];
NSString *secondString = [NSString stringWithCString:"Hello World!"
											encoding:NSUTF8StringEncoding];
NSString *thirdString = @"Hello World!";

Each of these examples effectively accomplishes the same thing—creating a string object that represents the provided characters.

The basic NSString class is immutable, which means its contents are set at creation and cannot later be changed. If you need to represent a different string, you must create a new string object, like this:

NSString *name = @"John";
name = [name stringByAppendingString:@"ny"];    // returns a new string object

The NSMutableString class is the mutable subclass of NSString, and allows you to change its character contents at runtime using methods like appendString: or appendFormat:, like this:

NSMutableString *name = [NSMutableString stringWithString:@"John"];
[name appendString:@"ny"];   // same object, but now represents "Johnny"



Format Strings Are Used to Build Strings from Other Objects or Values

If you need to build a string containing variable values, you need to work with a format string. This allows you to use format specifiers to indicate how the values are inserted:

int magicNumber = ...
NSString *magicString = [NSString stringWithFormat:@"The magic number is %i", magicNumber];

The available format specifiers are described in String Format Specifiers. For more information about strings in general, see the String Programming Guide.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值