1

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

Jteve Sobs
  • 244
  • 1
  • 14

1 Answers1

1

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.

zaph
  • 111,848
  • 21
  • 189
  • 228
  • so are you suggesting to use `stringByReplacingOccurancesOfString: withString:` to rid all the forward slashes? ? – Jteve Sobs Aug 13 '15 at 15:17
  • No, that would also remove the separator between the components, see the update answer. – zaph Aug 13 '15 at 15:21
  • I'm retrieving the strings from an array located on the server, so I don't know what the string is, thats why it was in a loop. So maybe I'm wrong here but i thought that was the right thing to do. I'm learning here, i'm learning. But i see how you got them directly in the NSLog, very clever. So if you can help me learn, i get the range starts with 1, so it's not like an array where it starts at 0, so i now get the location.length -2. That way it's not even considering the last /. Thank you – Jteve Sobs Aug 13 '15 at 15:35
  • 1
    NSRange starts with 0 but the first character needs to be skipped. – zaph Aug 13 '15 at 16:00