2014-01-21 6 views
1

나는 배열을 가지고있다.별도의 배열 아이폰 OS

문자열 배열의 마지막 문자를 기준으로이 배열을 여러 배열로 분리하려면 어떻게해야합니까? 배열이 변경 가능한지 여부는 중요하지 않습니다.

즉 ...

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