2014-01-21 34 views
1

我有一个数组:数组A包含对象独立阵列到新的阵列具有相似的对象 - iOS设备

"Anchorage, AK" 
"Juneau, AK" 
"Los Angeles, CA" 
"Minneapolis, MS" 
"Seatac, WA" 
"Seattle, WA" 

注:实际的数组对象不包含引号。

如何根据字符串的最后一个字符将此数组分成多个数组?如果数组是可变的或不对我无关紧要。

即...

Array 2 { 
[1] <--- First NSArray 
"Anchorage, AK" 
"Jeneau, AK" 

[2] <--- Second NSArray 
"Los Angeles, CA" 

[3] <--- Third NSArray 
"Minneapolis, MS" 

[4] <--- Fourth NSArray 
"Seatac, WA" 
"Seattle, WA" 
} 

在真实的情景,我将不知道有多少每个状态的也有。我在想我可以用字符串的两个char长度部分做些什么?因为这就是我想要他们分离出来的本质。

+0

试图实现的东西和发布非工作代码。我们不能只为你写。 –

+0

你想分割数组的标准是什么? –

+0

@JoshCaswell我想根据字符串对象中的最后两个字符对对象进行分组。 – Milo

回答

2

好的 - 让我知道这是否清楚。

// Setup the inital array 
NSArray *array = [[NSArray alloc] initWithObjects:@"Anchorage, AK", 
        @"Juneau, AK", 
        @"Los Angeles, CA", 
        @"Minneapolis, MS", 
        @"Seatac, WA", 
        @"Seattle, WA", nil]; 

// Create our array of arrays 
NSMutableArray *newArray2 = [[NSMutableArray alloc] init]; 

// Loop through all of the cities using a for loop 
for (NSString *city in array) { 
    // Keep track of if we need to creat a new array or not 
    bool foundCity = NO; 

    // This gets the state, by getting the substring of the last two letters 
    NSString *state = [city substringFromIndex:[city length] -2]; 

    // Now loop though our array of arrays tosee if we already have this state 
    for (NSMutableArray *subArray in newArray2) { 
     //Only check the first value, since all the values will be the same state 
     NSString *arrayCity = (NSString *)subArray[0]; 
     NSString *arrayState = [arrayCity substringFromIndex:[arrayCity length] -2]; 

     if ([state isEqualToString:arrayState]) 
     { 
      // Check if the states match... if they do, then add it to this array 
      foundCity = YES; 
      [subArray addObject:city]; 

      // No need to continue the for loop, so break stops looking though the arrays. 
      break; 
     } 
    } 

    // WE did not find the state in the newArray2, so create a new one 
    if (foundCity == NO) 
    { 
     NSMutableArray *newCityArray = [[NSMutableArray alloc] initWithObjects:city, nil]; 
     [newArray2 addObject:newCityArray]; 
    } 


} 

//Print the results 
NSLog(@"%@", newArray2); 

我的输出

2014-01-20 20:28:04.787 TemperatureConverter[91245:a0b] (
     (
     "Anchorage, AK", 
     "Juneau, AK" 
    ), 
     (
     "Los Angeles, CA" 
    ), 
     (
     "Minneapolis, MS" 
    ), 
     (
     "Seatac, WA", 
     "Seattle, WA" 
    ) 
) 
+0

但是,如果我不知道每个州有多少州,我该怎么办? – Milo

+0

我不明白你的目标,你究竟想要打破阵列呢?你遵循什么算法?第一个和最后一个数组是2,其余的是一个? – ansible

+0

我已说明我的问题 – Milo

0

您可以遍历原始数组中的字符串和split them by delimiters并将它们放入新数组中。然后,您可以根据数组中的第二个元素查看数组和组。

+0

您可以详细说明如何根据第二个元素对它们进行分组吗?我有一个数组,包含上述数组中的所有两个char状态名称。 – Milo