我正在使用以下内容以“,”分隔字符串:
NSString * receivedString = @"component1,component3,,component6";
NSArray * arrayOfSubstrings = [receivedString componentsSeparatedByString","];
但是我想保留“,”作为单独的组件并获取以下数组:
[0] "component1"
[1] ","
[2] "component2"
[4] ","
[5] ","
[6] "component6"
而不是:
[0] "component1"
[1] "component2"
[2] "component6"
基本上,“,”也是我要分析的元素。
知道如何在不重新发明轮子的情况下做到这一点吗?
Best Answer-推荐答案 strong>
(未测试)
+ (NSArray *)splitStringNSString *)string
withSeparatorNSString *)separator
{
NSArray *elements = [string componentsSeparatedByString:separator];
NSMutableArray *arr = [NSMutableArray new];
for (NSUInteger i = 0; i < [elements counts]; i++) {
NSString *element = elements[i];
if ([element length] > 0)
[arr addObject:element];
if (i != [elements count] - 1)
[arr addObject:separator];
}
return arr;
}
关于ios - 如何在保留分隔符的同时拆分 NSString,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/31938765/
|