Creating and Converting String Objects
NSString
and its subclass NSMutableString
provide several ways to create string objects, most based around the various character encodings it supports. Although string objects always present their own contents as Unicode characters, they can convert their contents to and from many other encodings, such as 7-bit ASCII, ISO Latin 1, EUC, and Shift-JIS. The availableStringEncodings class method returns the encodings supported. You can specify an encoding explicitly when converting a C string to or from a string object, or use the default C string encoding, which varies from platform to platform and is returned by the defaultCStringEncoding
class method.
- NSString及其子类NSMutableString提供了几种创建字符串对象的方法,大多数方法都基于它支持的各种字符编码。 尽管字符串对象始终将自己的内容显示为Unicode字符,但它们可以将其内容转换为许多其他编码,例如7位ASCII,ISO Latin 1,EUC和Shift-JIS。 availableStringEncodings类方法返回支持的编码。 您可以在将C字符串转换为字符串对象或从字符串对象转换时显式指定编码,或使用默认的C字符串编码,该编码因平台而异,并由defaultCStringEncoding类方法返回。
Creating Strings
The simplest way to create a string object in source code is to use the Objective-C @"..."
construct:
- 在源代码中创建字符串对象的最简单方法是使用Objective-C @“...”构造:
NSString *temp = @"Contrafibularity";
Note, when creating a string constant in this fashion, you should use UTF-8 characters. You can put the actual Unicode data in the string for localized text, as in NSString *hello = @"こんにちは";
. You can also insert \u
or \U
in the string for non-graphic characters.
- 请注意,以这种方式创建字符串常量时,应使用UTF-8字符。 您可以将实际的Unicode数据放入字符串中以用于本地化文本,如NSString * hello = @“こんにちは”;。 您还可以在非图形字符的字符串中插入\ u或\ U.
Objective-C string constant is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string:
- Objective-C字符串常量在编译时创建,并在整个程序执行期间存在。 编译器使这些对象常量在每个模块的基础上是唯一的,并且它们永远不会被释放。 您还可以像执行任何其他字符串一样将消息直接发送到字符串常量:
BOOL same = [@"comparison" isEqualToString:myString];
NSString from C Strings and Data
To create an NSString
object from a C string, you use methods such as initWithCString:encoding:. You must correctly specify the character encoding of the C string. Similar methods allow you to create string objects from characters in a variety of encodings. The method initWithData:encoding:
allows you to convert string data stored in an NSData
object into an NSString
object.
- 要从C字符串创建NSString对象,请使用initWithCString:encoding:等方法。 您必须正确指定C字符串的字符编码。 类似的方法允许您从各种编码的字符创建字符串对象。 方法initWithData:encoding:允许您将存储在NSData对象中的字符串数据转换为NSString对象。
char *utf8String = /* Assume this exists. */ ;
NSString *stringFromUTFString = [[NSString alloc] initWithUTF8String:utf8String];
char *macOSRomanEncodedString = /* assume this exists */ ;
NSString *stringFromMORString =
[[NSString alloc] initWithCString:macOSRomanEncodedString
encoding:NSMacOSRomanStringEncoding];
NSData *shiftJISData = /* assume this exists */ ;
NSString *stringFromShiftJISData =
[[NSString alloc] initWithData:shiftJISData
encoding:NSShiftJISStringEncoding];
The following example converts an NSString object containing a UTF-8 character to ASCII data then back to an NSString object.
- 以下示例将包含UTF-8字符的NSString对象转换为ASCII数据,然后再转换回NSString对象。
unichar ellipsis = 0x2026;
NSString *theString = [NSString stringWithFormat:@"To be continued%C", ellipsis];
NSData *asciiData = [theString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding];
NSLog(@"Original: %@ (length %d)", theString, [theString length]);
NSLog(@"Converted: %@ (length %d)", asciiString, [asciiString length]);
// output:
// Original: To be continued… (length 16)
// Converted: To be continued... (length 18)
Note: NSString
is not intended as a data storage container for arbitrary sequences of bytes. For this type of functionality, refer to NSData.
- NSString不用作任意字节序列的数据存储容器。 有关此类功能,请参阅NSData。
Variable Strings
To create a variable string, you typically use stringWithFormat:: or initWithFormat: (or for localized strings, localizedStringWithFormat:). These methods and their siblings use a format string as a template into which the values you provide (string and other objects, numerics values, and so on) are inserted. They and the supported format specifiers are described in Formatting String Objects.
- 要创建变量字符串,通常使用stringWithFormat ::或initWithFormat :(或用于本地化字符串,localizedStringWithFormat :)。 这些方法及其兄弟使用格式字符串作为模板,您可以在其中插入您提供的值(字符串和其他对象,数字值等)。 它们和支持的格式说明符在格式化字符串对象中描述。
You can build a string from existing string objects using the methods stringByAppendingString: and stringByAppendingFormat: to create a new string by adding one string after another, in the second case using a format string.
- 您可以使用方法stringByAppendingString:和stringByAppendingFormat:从现有字符串对象构建字符串,以通过在第二种情况下使用格式字符串添加一个字符串来创建新字符串。
NSString *hString = @"Hello";
NSString *hwString = [hString stringByAppendingString:@", world!"];
Strings to Present to the User
- 字符串呈现给用户
When creating strings to present to the user, you should consider the importance of localizing your application. In general, you should avoid creating user-visible strings directly in code. Instead you should use strings in your code as a key to a localization dictionary that will supply the user-visible string in the user's preferred language. Typically this involves using NSLocalizedString and similar macros, as illustrated in the following example.
- 在创建要呈现给用户的字符串时,您应该考虑本地化应用程序的重要性。 通常,您应该避免直接在代码中创建用户可见的字符串。 相反,您应该在代码中使用字符串作为本地化字典的键,该字典将以用户首选语言提供用户可见的字符串。 通常,这涉及使用NSLocalizedString和类似的宏,如以下示例所示。
NSString *greeting = NSLocalizedStringFromTable
(@"Hello", @"greeting to present in first launch panel", @"greetings");
For more about internationalizing your application, see Internationalization and Localization Guide. Localizing String Resources describes how to work with and reorder variable arguments in localized strings.
- 有关国际化应用程序的更多信息,请参阅“国际化和本地化指南”。 本地化字符串资源描述了如何在本地化字符串中使用和重新排序变量参数。
Combining and Extracting Strings
You can combine and extract strings in various ways. The simplest way to combine two strings is to append one to the other. The stringByAppendingString: method returns a string object formed from the receiver and the given argument.
- 您可以通过各种方式组合和提取字符串。 组合两个字符串的最简单方法是将一个字符串附加到另一个字符串。 stringByAppendingString:方法返回由接收者和给定参数形成的字符串对象。
NSString *beginning = @"beginning";
NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"];
// alphaAndOmega is @"beginning and end"
You can also combine several strings according to a template with the initWithFormat:, stringWithFormat:, and stringByAppendingFormat: methods; these are described in more detail in Formatting String Objects.
- 您还可以根据模板将多个字符串与initWithFormat:,stringWithFormat:和stringByAppendingFormat:方法组合在一起; 这些在格式化字符串对象中有更详细的描述。
You can extract substrings from the beginning or end of a string to a particular index, or from a specific range, with the substringToIndex:, substringFromIndex:, and substringWithRange: methods. You can also split a string into substrings (based on a separator string) with the componentsSeparatedByString: method. These methods are illustrated in the following examples—notice that the index of the index-based methods starts at 0
:
- 您可以使用substringToIndex:,substringFromIndex:和substringWithRange:方法从字符串的开头或结尾将子字符串提取到特定索引,或从特定范围提取子字符串。 您还可以使用componentsSeparatedByString:方法将字符串拆分为子字符串(基于分隔符字符串)。 以下示例说明了这些方法 - 请注意,基于索引的方法的索引从0开始:
NSString *source = @"0123456789";
NSString *firstFour = [source substringToIndex:4];
// firstFour is @"0123"
NSString *allButFirstThree = [source substringFromIndex:3];
// allButFirstThree is @"3456789"
NSRange twoToSixRange = NSMakeRange(2, 4);
NSString *twoToSix = [source substringWithRange:twoToSixRange];
// twoToSix is @"2345"
NSArray *split = [source componentsSeparatedByString:@"45"];
// split contains { @"0123", @"6789" }
If you need to extract strings using pattern-matching rather than an index, you should use a scanner—see Scanners.
- 如果需要使用模式匹配而不是索引来提取字符串,则应使用扫描程序 - 请参阅扫描程序。
Getting C Strings
To get a C string from a string object, you are recommended to use UTF8String
. This returns a const char *
using UTF8 string encoding.
- 要从字符串对象获取C字符串,建议您使用UTF8String。 这将使用UTF8字符串编码返回const char *。
The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of the const char *
returned by the method.
- 您收到的C字符串由临时对象拥有,并且在自动释放时将变为无效。 如果要获取永久C字符串,则必须创建缓冲区并复制方法返回的const char *的内容。
Similar methods allow you to create string objects from characters in the Unicode encoding or an arbitrary encoding, and to extract data in these encodings. initWithData:encoding:
and dataUsingEncoding:
perform these conversions from and to NSData
objects.
- 类似的方法允许您使用Unicode编码或任意编码的字符创建字符串对象,并提取这些编码中的数据。 initWithData:encoding:和dataUsingEncoding:从NSData对象执行这些转换。
Conversion Summary
This table summarizes the most common means of creating and converting string objects:
-
此表总结了创建和转换字符串对象的最常用方法: