如何获得NSString的子string?

如果我想从NSString @"value:hello World:value"得到一个值,我该用什么?

我想要的返回值是@"hello World"

选项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" 

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

尽pipe如此,这个可能有点过分了。

备选案文3:

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

这一个创build三个临时string和一个数组,同时分裂。


所有片段都假定search的内容实际上包含在string中。

这是一个稍微复杂一点的答案:

 NSString *myString = @"abcdefg"; NSString *mySmallerString = [myString substringToIndex:4]; 

另请参阅substringWithRange和substringFromIndex

这是一个简单的function,可以让你做你正在寻找的东西:

 - (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator { NSRange firstInstance = [value rangeOfString:separator]; NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator]; NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location); return [value substringWithRange:finalRange]; } 

用法:

 NSString *myName = [self getSubstring:@"This is my :name:, woo!!" betweenString:@":"]; 

这里是@Regexident Option 1和@Garett答案的一个小组合,以便在前缀和后缀之间获得一个强大的string切割器,其中包含MORE … ANDMORE字样。

 NSString *haystack = @"MOREvalue:hello World:valueANDMORE"; NSString *prefix = @"value:"; NSString *suffix = @":value"; NSRange prefixRange = [haystack rangeOfString:prefix]; NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix]; NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location); NSString *needle = [haystack substringWithRange:needleRange]; NSLog(@"needle: %@", needle); 

也使用这个

 NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)]; 

注意 – 你的NSMakeRange(start, end)应该是NSMakeRange(start, end- start) ;