0

我正在尝试将一个字符串解析为一个数组,每个项目都在 <> 之间,例如<this is column 1><this is column 2>等等......

帮助将不胜感激。

谢谢

4

3 回答 3

2

要证明的东西:

NSString *string = @"<this is column 1><this is column 2>";
NSScanner *scanner = [NSScanner scannerWithString:string];

NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];

NSString *temp;

while ([scanner isAtEnd] == NO)
{
    // Disregard the result of the scanner because it returns NO if the
    //  "up to" string is the first one it encounters.
    // You should still have this in case there are other characters
    //  between the right and left angle brackets.
    (void) [scanner scanUpToString:@"<" intoString:NULL];

    // Scan the left angle bracket to move the scanner location past it.
    (void) [scanner scanString:@"<" intoString:NULL];

    // Attempt to get the string.
    BOOL success = [scanner scanUpToString:@">" intoString:&temp];

    // Scan the right angle bracket to move the scanner location past it.
    (void) [scanner scanString:@">" intoString:NULL];

    if (success == YES)
    {
        [array addObject:temp];
    }
}

NSLog(@"%@", array);
于 2012-12-14T16:13:29.800 回答
1

一种方法可能是使用NSString 中的componentsSeparatedByCharactersInSetcomponentsSeparatedByString

NSString *test = @"<one> <two> <three>";

NSArray *array1 = [test componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];

NSArray *array2 = [test componentsSeparatedByString:@"<"];

之后您需要进行一些清理,在array2的情况下进行修剪或在array1的情况下删除空白字符串

于 2012-12-14T16:13:08.593 回答
1
NSString *input =@"<one><two><three>";
NSString *strippedInput = [input stringByReplacingOccurencesOfString: @">" withString: @""]; //strips all > from input string
NSArray *array = [strippedInput componentsSeperatedByString:@"<"];

请注意, [array objectAtIndex:0] 将是一个空字符串(“”),如果“实际”字符串之一包含 < 或 >,这当然不起作用

于 2012-12-14T16:37:43.863 回答