Position of a character in a NSString or NSMutableString

半城伤御伤魂 提交于 2019-11-29 02:47:48

问题


I have searched for hours now and haven't found a solution for my problem. I have a NSString which looks like the following:

"spacer": ["value1", "value2"], "spacer": ["value1", "value2"], ...

What I want to do is to remove the [ ] characters from the string. It's seems to be impossible with objective-c. Most other programming languages offer functions like strpos or indexOf which allow me to search for a character or string and locate the position of it. But there seems nothing to be like this in objective-c.

Does anyone has an idea on how to remove these characters? Additionally there are [] characters in the string which should remain, so I can't just use NSMutableString stringByReplacingOccurencesOfString:withString. I need to search first for the spacer string and then remove only the next two [] chars.

Thank you for helping me.


回答1:


To find occurrences of a string within a string, use the rangeOfXXX methods in the NSString class. Then you can construct NSRanges to extract substrings, etc.

This example removes only the first set of open/close brackets in your sample string...

NSString *original = @"\"spacer\": \[\"value1\", \"value2\"], \"spacer\": \[\"value1\", \"value2\"]";
NSLog(@"%@", original);

NSRange startRange = [original rangeOfString:@"\["];
NSRange endRange = [original rangeOfString:@"]"];

NSRange searchRange = NSMakeRange(0, endRange.location);
NSString *noBrackets = [original stringByReplacingOccurrencesOfString:@"\[" withString:@"" options:0 range:searchRange];
noBrackets = [noBrackets stringByReplacingOccurrencesOfString:@"]" withString:@"" options:0 range:searchRange];
NSLog(@"{%@}", noBrackets);

The String Programming Guide has more details.
You might alternatively also be able to use the NSScanner class.




回答2:


This worked for me to extract everything to the index of a character, in this case '[':

NSString *original = @"\"spacer\": \[\"value1\", \"value2\"], \"spacer\": \[\"value1\", \"value2\"]";
NSRange range = [original rangeOfString:@"\["];
NSString *toBracket = [NSString stringWithString :[original substringToIndex:range.location] ];
NSLog(@"toBracket: %@", toBracket);


来源:https://stackoverflow.com/questions/2379997/position-of-a-character-in-a-nsstring-or-nsmutablestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!