find range of substring of string

前端 未结 3 1228
清酒与你
清酒与你 2020-12-29 05:37

I am trying to figure out how to get a range of a substring within a string. By range I mean where the substring begins and where it ends. So if I have following string exam

相关标签:
3条回答
  • 2020-12-29 06:29

    It is pretty straight forward. You say you want to search the string "hello everyone how are you doing today?Thank you!" for "how are you doing".

    You say you need the position of the first character and the last.

    NSString *testString=@"hello everyone how are you doing today?Thank you!";
    
    NSRange range = [testString rangeOfString:@"how are you doing"];
    
    NSUInteger firstCharacterPosition = range.location;
    NSUInteger lastCharacterPosition = range.location + range.length;
    

    So now you have it those two last variables.

    0 讨论(0)
  • 2020-12-29 06:34

    Use the built in method part of NSString:

    [testString rangeOfString:@"hello how are you doing"]
    

    Documentation: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-rangeOfString_

    0 讨论(0)
  • 2020-12-29 06:39

    You can use the method -rangeOfString to find the location of a substring in a string. You can then compare the location of the range to NSNotFound to see if the string actually does contain the substring.

    NSRange range = [testString rangeOfString:@"how are you doing"];
    
    if (range.location == NSNotFound) {
        NSLog(@"The string (testString) does not contain 'how are you doing' as a substring");
    }
    else {
        NSLog(@"Found the range of the substring at (%d, %d)", range.location, range.location + range.length);        
    }
    
    0 讨论(0)
提交回复
热议问题