从字符串变量获取子字符串并保存到NSMutableArray

时间:2016-02-01 06:43:48

标签: ios objective-c nsstring nsmutablearray substring

我是iOS开发的新手,面临一些问题。我有一个这样的字符串M||100|??|L||150|??|S||50.我想将字符串分成块并保存到数组中,e.g M 100在第一个索引上,L 150在第二个索引上,S 50在第三个索引上。< / p>

5 个答案:

答案 0 :(得分:2)

您可以使用此代码

从字符串中获取数组
NSString *str = @"M||100|??|L||150|??|S||50";
str = [str stringByReplacingOccurrencesOfString:@"||" withString:@" "];
NSArray *array = [str componentsSeparatedByString:@"|??|"];  

这将返回您的预期结果。

答案 1 :(得分:2)

NSString *str = @"M||100|??|L||150|??|S||50";
NSString *stringWithoutBars = [str stringByReplacingOccurrencesOfString:@"||" withString:@" "];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[stringWithoutBars componentsSeparatedByString:@"|??|"]];

答案 2 :(得分:0)

let str = "M||100|??|L||150|??|S||50"
let array = str.componentsSeparatedByString("|??|")
print(array)

结果:

["M||100", "L||150", "S||50"]

答案 3 :(得分:0)

///First replace "||" with " "

NSString *your_str = @"M||100|??|L||150|??|S||50";
your_str = [your_str stringByReplacingOccurrencesOfString:@"||" withString:@" "];

///Get array of string

NSArray *arr = [your_str componentsSeparatedByString:@"|??|"];
NSMutableArray *data_arr = [[NSMutableArray alloc] init];
for(NSString *str in arr)
{
   ///string to data conversion
   NSData *data = [your_str dataUsingEncoding:NSUTF8StringEncoding];

   //////// add data to array
   [data_arr addObject: data];
}
NSLog(@"data_arr =%@",data_arr);

答案 4 :(得分:0)

NSString *str = @"M||100|??|L||150|??|S||50";
NSArray *arrt = [str componentsSeparatedByString:@"|??|"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i = 0; i <= arrt.count - 1; i++) {
    [arr addObject:[[arrt objectAtIndex:i] componentsSeparatedByString:@"||"]];
}