您的位置:首页 > 移动开发 > Objective-C

objective-c怎么将一个字符串分割成多个字符串

2015-06-16 15:54 561 查看
可以用NSString类的 - (NSArray *)componentsSeparatedByString:(NSString *)separator函数实现。
例子:
假如有一个字符串
NSString *list = @"Karin, Carrie, David";
可以用上面的函数得到一个字符串数组:

NSArray *listItems = [list componentsSeparatedByString:@", "];
这个数组就是把原来的字符串用","分割得到的多个字符串:
{ @"Karin", @"Carrie", @"David"" }

下面是苹果官方NSString类的说明:
链接地址:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:

Objective-C

- (NSArray *)componentsSeparatedByString:(NSString *)separator

Parameters

separator

The separator string.

Return Value

An NSArray object containing substrings from the receiver that have been divided by separator.

Discussion

The substrings in the array appear in the order they did in the
receiver. Adjacent occurrences of the separator string produce empty
strings in the result. Similarly, if the string begins or ends with the
separator, the first or last substring, respectively, is empty. For
example, this code fragment:

NSString *list = @"Karin, Carrie, David";
NSArray *listItems = [list componentsSeparatedByString:@", "];

produces an array { @"Karin", @"Carrie", @"David"" }.

If list begins with a comma and space—for example, @", Norman, Stanley, Fletcher"—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }

If list has no separators—for example, "Karin"—the array contains the string itself, in this case { @"Karin" }.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: