Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 预定义字符串之间的NSString子字符串_Ios_Objective C_Nsstring - Fatal编程技术网

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

Ios 预定义字符串之间的NSString子字符串,ios,objective-c,nsstring,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 - %

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

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

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

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");
}

您可以使用
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中输入的所有代码,不包括错误处理

查看NSString的
rangeOfString
函数。
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)];