开发者

How to get a Substring from a String?

开发者 https://www.devze.com 2023-01-03 12:15 出处:网络
I have a little question ,I have a NSString object (\\n \"1 Infinite Loop\",\\n \"Cupertino, CA 95014\",\\n USA\\n)

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.

开发者_StackOverflow中文版Is any other method able to solve this problem?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消