views:

415

answers:

2

Hi all,

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.

Do any other method able to solve this problem?

+2  A: 

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];
luvieere
hi luvieere,thanks for reply but i want to get the substring present within starting of 2nd double quote and 1st comma of double quote(Ex.Cupertino) and as my string is dynamic so i can not able fix the range for it.
raaz
@raaz check to see the new solution
luvieere
Hi Luvieere,It work like a charm.Thanx for the help
raaz
A: 

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.

walkytalky