从范围在特殊字符之间的字符串中提取字符串

Extract string from string with ranges inbetween special characters

我有一条路径,我正在以字符串的形式检索它。我想将字符串分成两个不同的段,但我使用的方法在数组中给出了错误的对象。

假设我有路径:

/Country/State/ 

我正在检索它并尝试像这样分开这两个词:

    NSArray *tempArray = [serverArray valueForKey:@"Location"];

    NSArray *country;
    for (NSString *string in tempArray) {
       country = [string componentsSeparatedByString:@"/"];
        NSLog(@"%@", country);
    }

但是当我这样做时,我在记录它们时在数组中得到了两个额外的对象:

2015-08-13 10:54:17.290 App Name[24124:0000000] (
"",
USA,
"NORTH DAKOTA",
""
)

如何获取第一个没有特殊字符的字符串,然后第二个字符串也没有特殊字符?之后我打算使用 NSScanner 但不确定是否有更有效的方法

那是因为有前导和尾随 / 个字符。

一个选项是对初始字符串进行子字符串化以删除前导和尾随 / 个字符。

示例:

NSString *location = @"/Country/State/";
location = [location substringWithRange:NSMakeRange(1, location.length-2)];
NSArray *components = [location componentsSeparatedByString:@"/"];
NSLog(@"components[0]: %@, components[1]: %@", components[0], components[1]);
NSLog(@"components: %@", components);

输出:

components[0]: Country, components[1]: State

components: (
    Country,
    State
)

也不需要 for 循环。不要添加代码行,除非您知道为什么并且知道它们是必需的。