Position of a character in a NSString or NSMutableString

后端 未结 2 1495
醉酒成梦
醉酒成梦 2020-12-29 10:32

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\", \"valu

相关标签:
2条回答
  • 2020-12-29 11:08

    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.

    0 讨论(0)
  • 2020-12-29 11:10

    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);
    
    0 讨论(0)
提交回复
热议问题