牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2015-06-16 投稿人: 浏览次数:1110
可以用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" }.
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。