如何拆分NSString并将其重新加入两个NSStrings?

时间:2014-09-01 11:24:37

标签: ios iphone split nsstring dynamic-programming

我有一个像这样的NSString:

NSString* allSeats = @"1_Male,2_Female,3_Female,4_Male";

我想根据关键字 _Male &分拆NSString _Female 然后制作两个单独的字符串:

NSString* maleSeats = @"1,4";
NSString* femaleSeats = @"2,3";

基于上面声明的allSeats变量的内容。

如何分割NSString然后分成两个单独的字符串?

2 个答案:

答案 0 :(得分:0)

你必须自己做。没有“全部完成”的解决方案。有几种方法可以做到。

注意:我没有尝试我的代码,我只是编写它,它可能甚至不编译。但重要的是你要了解它背后的全部想法。

一种方式可能就是这个:

NSString *maleSufffix = @"_Male";
NSString *femaleSufffix = @"_Female";
NSMutableArray *femaleSeatsArray = [[NSMutableArray alloc] init];
NSMutableArray *maleSeatsArray = [[NSMutableArray alloc] init];
NSArray *array = [allSeats componentsSeparatedByString:@","];
for (NSString *aSeat in array)
{
    if ([aSeat hasSuffix:maleSuffix])
    {
        [maleSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:maleSuffix withString:@""]];
    }
    else if ([aSeat hasSuffix:femaleSuffix])
    {
        [femalSeatsArray addObject:[aSeat stringByReplacingOccurencesOfString:femaleSuffix withString:@""]];
    }
     else
    {
          NSLog(@"Unknown: %@", aSeat);
    }
}
NSString *maleSeats = [maleSeatsArray componentsJoinedByString:@","];
NSString *femaleSeats = [femaleSeatsArray componentsJoinedByString:@","];

当然,您可以在array上使用不同的方法,枚举它,使用NSMutableString代替NSMutableArrayfemaleSeatsArraymaleSeatsArray,然后在for循环中使用适当的方法。

答案 1 :(得分:-1)

我从Larme的线索中得出了一个想法,它的作用如下:

制作方法并在任何地方调用它:

- (无效)seperateSeat

{

maleSufffix = @"_Male";

femaleSufffix = @"_Female";

femaleSeatsArray = [[NSMutableArray alloc] init];

maleSeatsArray = [[NSMutableArray alloc] init];

array = [self.selectedPassengerSeat componentsSeparatedByString:@","];

for (aSeat in array)
{
    if ([aSeat hasSuffix:maleSufffix])
    {
        aSeat = [aSeat substringToIndex:[aSeat length]-5];
        NSLog(@"%@ is value in final seats ::",aSeat );

        [maleSeatsArray addObject:aSeat];
    }
    else if ([aSeat hasSuffix:femaleSufffix])
    {
        aSeat = [aSeat substringToIndex:[aSeat length]-7];
        NSLog(@"%@ is value in final seats ::",aSeat );

        [femaleSeatsArray addObject:aSeat];
    }
}    

totalMales = [maleSeatsArray componentsJoinedByString:@","];
totalFemales = [femaleSeatsArray componentsJoinedByString:@","];
NSLog(@"maleSeatsAre::::%@",totalMales);
NSLog(@"maleSeatsAre::::%@",totalFemales);

}