Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/113.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 从字符串中提取数字_Ios_Xcode - Fatal编程技术网

Ios 从字符串中提取数字

Ios 从字符串中提取数字,ios,xcode,Ios,Xcode,我有很多这样的字符串: @"this is the content. The content of this string may vary, as well as the length, and my include any characters, with numbers Y = 295.000000 X = 207.500000" coordsFinal.x = 295.000000; coordsFinal.y = 207.500000; 部分Y=295.000000 X=207.5

我有很多这样的字符串:

@"this is the content. The content of this string may vary, as well as the length, and my include any characters, with numbers Y = 295.000000 X = 207.500000"
coordsFinal.x = 295.000000;
coordsFinal.y = 207.500000;
部分Y=295.000000 X=207.500000始终保持不变,但X和Y数字可能会改变

我需要以某种方式获得这些数字,并执行以下操作:

@"this is the content. The content of this string may vary, as well as the length, and my include any characters, with numbers Y = 295.000000 X = 207.500000"
coordsFinal.x = 295.000000;
coordsFinal.y = 207.500000;
其格式为:

coordsFinal.x = [NSString stringWithFormat: @"%@", trimmed string];

有什么想法吗?

您可以使用正则表达式提取数字:

NSString *string = ...; // Your string
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"Y = (\\d+.\\d+) X = (\\d+.\\d+)" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (match) {
    NSRange yRange = [match rangeAtIndex:1];
    NSString *yString = [string substringWithRange:yRange];
    NSRange xRange = [match rangeAtIndex:2];
    NSString *xString = [string substringWithRange:xRange];

    NSLog(@"X = %@, Y = %@", xString, yString);
}
输出:


您可以使用正则表达式提取数字:

NSString *string = ...; // Your string
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"Y = (\\d+.\\d+) X = (\\d+.\\d+)" options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
if (match) {
    NSRange yRange = [match rangeAtIndex:1];
    NSString *yString = [string substringWithRange:yRange];
    NSRange xRange = [match rangeAtIndex:2];
    NSString *xString = [string substringWithRange:xRange];

    NSLog(@"X = %@, Y = %@", xString, yString);
}
输出:


您只需要以下方法来调用要修剪的字符串

 [yourstring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

您只需要以下方法来调用要修剪的字符串

 [yourstring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]