Objective-C中的componentsSeparatedByString是什么意思?

3

componentsSeparatedByString 在 Objective-C 中的含义是什么?

NSArray *customerNameArray=[[[arrTemp objectAtIndex:0] objectForKey:@"CustomerNames"] componentsSeparatedByString:@";"];

在上述代码中,arrTempMSMutableArray的一个对象。它被用在哪里?

5
如果您有类似“这个方法是做什么的?”的问题,请务必阅读文档。http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html - Stanislav Yaglo
4个回答

9

componentsSeparatedByString: 类似于 Java 中的 StringTokenizer。它会根据给定的分隔符将给定字符串拆分成一个数组。例如,

NSString *namesStr =  @"John;Michael;Jason";
NSArray *namesArray = [namesStr componentsSeparatedByString:@";"];

因此,namesArray将包含字符串@"John"@"Michael"@"Jason"

如果字符串是这样的:@"John;;;Michael;;Jason",会发生什么? - user3164248

5

0

假设你有以下字符串。

// [[arrTemp objectAtIndex:0] objectForKey:@"CustomerNames"] => "John,Steve,Bob"

当你这样做时:

NSArray *names = [[[arrTemp objectAtIndex:0] objectForKey:@"CustomerNames"] componentsSeparatedByString:@";"];
// names => ["John", "Steve", "Bob"]

所以你可以使用这些东西:

[names objectAtIndex:0] // => John
[names count] // => 3

0

componentsSeparatedByString - 返回一个数组,其中包含已由给定分隔符分割的接收器中的子字符串。

数组中的子字符串按照它们在接收器中出现的顺序出现。分隔符字符串的相邻出现会在结果中产生空字符串。同样,如果字符串以分隔符开头或结尾,则第一个或最后一个子字符串为空。例如,此代码片段:

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

生成数组 @[@"Karin", @"Carrie", @"David"]。

如果列表以逗号和空格开头,例如@“,Norman,Stanley,Fletcher”,则数组包含以下内容:@[@"", @"Norman", @"Stanley", @"Fletcher"]。

如果列表没有分隔符,例如@“Karin”,则数组包含字符串本身,在这种情况下为@[@"Karin"]。

Apple参考文档:componentsSeparatedByString:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接