0

我有一个 NSStrings 的 NSMutableArray,其中数组的每个元素的格式等于 @"key is 1::value is 1"。现在我想将“::”之前的字符串部分存储在array1中,将“::”之后的字符串部分存储在array2中。我怎样才能做到这一点?

4

5 回答 5

0

我找到了方法。在迭代原始数组的元素时,我将分别在数组 1 和数组 2 中添加 beforeString 和 afterString

for(int i=0;i<self.originalArray.count;i++)
    {
      NSString *temp=[self.originalArray objectAtIndex:i];

        NSRange r = [temp rangeOfString:@"::"];
        NSString *beforeString = [temp substringToIndex:r.location];
        NSString *afterString = [temp substringFromIndex:r.location+2];

        [array1 addObject:beforeString];  
        [array2 addObject:afterString];  
     }
于 2013-01-23T04:42:30.680 回答
0

拆分字符串的关键是使用 NSString 上的componentsSeparatedByString:方法将字符串拆分为 NSArray。阅读有关此方法如何处理空白字符串等的文档,但这就是您要使用的。

您说您有一个字符串数组,因此基本实现将涉及迭代该数组并将每个元素添加到其他两个数组。

NSMutableArray *arrayOfStrings = [NSMutableArray array];
NSMutableArray *array1 = [NSMutableArray array];
NSMutableArray *array2 = [NSMutableArray array];

for (NSString *string in arrayOfStrings)
{
    NSArray *components = [string componentsSeparatedByString:@"::"];
    if ([components count] == 2)
    {
        NSString *obj1 = [components objectAtIndex:0];
        NSString *obj2 = [components objectAtIndex:1];
        [array1 addObject:obj1];
        [array2 addObject:obj2];
    }
}
于 2013-01-23T04:21:06.760 回答
0

这是代码:

NSArray *temp = [YourString componentsSeparatedByString:@"::"];
NSString *str1 = [temp objectAtIndex:0];
NSString *str2 = [temp objectAtIndex:1];

但在访问数组中的对象之前.. 检查它是否包含该值。

于 2013-01-23T04:24:43.703 回答
0

用这个:

[array1 addObject:[[YourString componentsSeparatedByString:@"::"] objectAtIndex:0]];
[array2 addObject:[[YourString componentsSeparatedByString:@"::"] objectAtIndex:1]];
于 2013-01-23T04:25:12.260 回答
0

尝试这个 ::

NSString *s = @"key is 1::value is 1";

NSArray *a = [s componentsSeparatedByString:@"::"];

NSLog(@" -> %@ --> %@", [a objectAtIndex:0], [a objectAtIndex:1]);
于 2013-01-23T04:27:20.187 回答