今天看到 ObjC 中国 上的 玩转字符串 这篇文章才发现原来有好多未知的用法啊,以后一定要多看看这些优质文章
指定位置格式化
[NSString stringWithFormat:@"%2$@ %1$@", @"1st", @"2nd"];
// "2nd 1st"
多行文字字面量
编译器的确有一个隐蔽的特性:把空格分隔开的字符串衔接到一起。这是什么意思呢?这段代码:
NSString *limerick = @"A lively young damsel named Menzies\n"
@"Inquired: «Do you know what this thenzies?»\n"
@"Her aunt, with a gasp,\n"
@"Replied: "It's a wasp,\n"
@"And you're holding the end where the stenzies.\n";
与下面这段代码是完全等价的:
NSString *limerick = @"A lively young damsel named Menzies\nInquired: «Do you know what this thenzies?»\nHer aunt, with a gasp,\nReplied: "It's a wasp,\nAnd you're holding the end where the stenzies.\n";
前者看起来更舒服,但是有一点要注意:千万不要在任意一行末尾加入逗号或者分号。
你也可以这样做:
NSString * string = @"The man " @"who knows everything " @"learns nothing" @".";
遍历字符
什么是字符?
例如:"The weather on 🌍 is 🌞 today" 肉眼所见的每个字母和 Emoji 表情都成为一个「字符」
我们通过 [NSString length]
获取到的长度,并不是字符的个数,这里的 Emoji 表情就被算成了 2 个长度
NSString
给我们提供了遍历字符的方法 ``
NSString *str = @"The weather on \U0001F30D is \U0001F31E today.";
[str enumerateSubstringsInRange:NSRangeMake(0, str.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
{
NSLog(@"%@ %@", substring, NSStringFromRange(substringRange));
}];
更多请移步:玩转字符串 NSString 与 Unicode