预定义字符串之间的NSString子字符串

时间:2014-02-10 15:10:48

标签: ios objective-c nsstring

如何在预定义字符串之间获取子字符串。例如:

NSString* sentence = @"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = @"{start}";
NSString* end = @"{end}";
NSString* myWord = [do some stuff with:sentence and:start and:end];

NSLog(@"myWord - %@",myWord);

Log: myWord - this

3 个答案:

答案 0 :(得分:2)

以下内容将为您提供所需的输出:

NSString* sentence = @"Here is my sentence. I am looking for {start}this{end} word";
NSString* start = @"{start}";
NSString* end = @"{end}";

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];

if (startRange.location != NSNotFound && endRange.location != NSNotFound) {
    NSString *myWord = [sentence substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length)];
    NSLog(@"myWord - %@", myWord);
}
else {
    NSLog(@"myWord not found");
}

答案 1 :(得分:0)

您可以使用rangeOfString:获取每个标记的位置。然后使用subStringWithRange:提取所需的字符串部分。

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence end];
NSString myWord = [NSString subStringWithRange:NSMakeRange(startRange.location+startRange.length, endRange.location-startRange.location+startRange.length)];

所有代码都在Safari中输入,并且不包含任何错误处理!

答案 2 :(得分:0)

NSRange startRange = [sentence rangeOfString:start];
NSRange endRange = [sentence rangeOfString:end];

int startLocation = startRange.location + startRange.length;
int lenght = endRange.location - startLocation;

NSString* myWord = [sentence substringWithRange:NSMakeRange(startLocation, lenght)];