raaz
raaz

Reputation: 12500

How to get a Substring from a String?

I have a little question ,I have a NSString object (\n "1 Infinite Loop",\n "Cupertino, CA 95014",\n USA\n)

and i want the substring present within 2nd double quote and first comma of 2nd double quote (Ex.Cupertino) from this string.(Note: My string is Dynamic)

Till now I have used stringByReplacingOccurrencesOfString: and able to get "1InfiniteLoop""CupertinoCA95014"USA

But still not able get Cupertino.

Is any other method able to solve this problem?

Upvotes: 1

Views: 13204

Answers (2)

walkytalky
walkytalky

Reputation: 9543

This depends a lot on how consistent the structure of your original string is in terms of the delimiting characters.

If it will always be exactly as posted, luvieere's answer is very nice and compact.

If the layout will always be consistent, but the content of each string may not -- for example, if the first address line might contain a comma -- it would be better to use two passes:

// remember, kids: hard coded number literals are evil
NSString* secondQuotedString = (NString*)[[componentsSeparatedByString:@"\""] objectAtIndex:3];
NSString* upToComma = (NString*)[[componentsSeparatedByString:@","] objectAtIndex:0];

If the nested structure is unreliable -- for example, if there might be escaped quote characters inside the strings -- then you'd need to do some additional parsing to avoid problems.

Upvotes: 1

luvieere
luvieere

Reputation: 37534

Use a substringWithRange: :

NSRange r = NSMakeRange(20, 29);
NSString *cup = [yourString substringWithRange: r];

After the explanation in your comment, I'd say

NSString *cup = (NSString*)[[yourString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @",\""]] objectAtIndex: 4];

Upvotes: 13

Related Questions