03. Creating and Converting String Objects

相关链接:
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html#//apple_ref/doc/uid/20000148-CJBCJHHI

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:

  • 此表总结了创建和转换字符串对象的最常用方法:


    image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,322评论 0 10
  • 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
    oceanfive阅读 3,067评论 0 7
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,695评论 0 3
  • 【慢点俱乐部】易效能初级学习100天第一阶段 3组 叶茗兮 20171024 心得打卡 【1-14讲理论模块】 ...
    12_叶茗兮阅读 193评论 0 1
  • 1、通过终端安装CocoaPods $sudo gem install cocoapods //听说(http:/...
    cocoaZ阅读 218评论 0 0