我有一个数组:包含对象的数组A
"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 :(得分: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"
)
)
答案 1 :(得分:0)
您可以遍历原始数组中的字符串split them by delimiters并将它们放入新数组中。然后,您可以根据数组中的第二个元素查看数组和组。