8

I have this NSString

Asia/Tokyo 

I want to get only "Tokyo" by removing "Asia/" I know it will get to work by searching for the position of "/" but how do i do that? pls help

1

4 Answers 4

15

To get the location of a substring in a string :

[@"Asia/Tokyo" rangeOfString:@"/"].location 
Sign up to request clarification or add additional context in comments.

1 Comment

Note this will find the first instance of the substring. You can use rangeOfString:options:range if you want to find other instances, or search backwards, or other things covered by the options.
7

You can use this as well:

NSString *mainString = @"Asia/Tokyo"; NSUInteger location = [mainString rangeOfString:@"/"].location + 1; NSLog(@"Trimed string:%@",[mainString substringFromIndex:location]); 

Result: Trimed string:Tokyo

Comments

0

Just split the string with componentsSeparatedByString:@"/" This'll return an array, and you just grab the second element.

6 Comments

That's overkill when you simply need the index of a character.
Unless this is performance-critical code, [input componentsSeparatedByString:@"/"][1] is a perfectly good solution.
@robmayoff Yes, it works but the thought of scanning the entire string for the delimiter, creating a temporary array full of strings I don't actually need, just to get the index of a character, makes me shiver.
@rmaddy Although the question was how to get the index, the OP isn't actually trying to get the position of the character, he's trying to get the substring delimited by the character.
@David Then use substringFromIndex: to get the needed substring after getting the range of the delimiter.
|
0

You can use rangeOfString to give you the location of string. I would also run the range through an if statement looking for NSNotFound just in case the string you are looking for isn't found.

Check out this answer for an example.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.