How to get substring of NSString?

后端 未结 5 966
孤城傲影
孤城傲影 2020-12-01 02:44

If I want to get a value from the NSString @\"value:hello World:value\", what should I use?

The return value I want is @\"hello World\".

5条回答
  •  一生所求
    2020-12-01 03:17

    Option 1:

    NSString *haystack = @"value:hello World:value";
    NSString *haystackPrefix = @"value:";
    NSString *haystackSuffix = @":value";
    NSRange needleRange = NSMakeRange(haystackPrefix.length,
                                      haystack.length - haystackPrefix.length - haystackSuffix.length);
    NSString *needle = [haystack substringWithRange:needleRange];
    NSLog(@"needle: %@", needle); // -> "hello World"
    

    Option 2:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
    NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
    NSRange needleRange = [match rangeAtIndex: 1];
    NSString *needle = [haystack substringWithRange:needleRange];
    

    This one might be a bit over the top for your rather trivial case though.

    Option 3:

    NSString *needle = [haystack componentsSeparatedByString:@":"][1];
    

    This one creates three temporary strings and an array while splitting.


    All snippets assume that what's searched for is actually contained in the string.

提交回复
热议问题