Jteve Sobs
Jteve Sobs

Reputation: 244

Extract string from string with ranges inbetween special characters

I have a path, that I am retrieving in the form of a string. I would like to segregate the string into two different segments, but the method I am using gives me erroneous objects in the array.

Lets say I have path :

/Country/State/ 

I am retrieving it and trying to separate the two words like this:

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

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

But when I do this I get two extra objects in the array when I log them :

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

How do I get the first string without special characters and then the second string without the special characters as well? After that I was going to use NSScanner but not sure if there is a more efficient way

Upvotes: 1

Views: 47

Answers (1)

zaph
zaph

Reputation: 112857

That is because there are leading and trailing / characters.

One option is to substring the initial string to remove the leading and trailing / characters.

Example:

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);

Output:

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

components: (
    Country,
    State
)

Also the for loop is not needed. Do not add lines of code unless you know why and that they are needed.

Upvotes: 1

Related Questions