我需要从字符串中获取子字符串CODE
的值(X2.31
)
NSString *str = @"SHMU=\"\" CODE=\"X2.31\" XTN=\";
我怎么能得到那个特定的子字符串?
试试下面的
NSString *str = @"SHMU=\"\" CODE=\"X2.31\" XTN=\"";
NSRange range = [str rangeOfString:@"CODE="];
NSString *substring = [[str substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *str1 = [substring componentsSeparatedByString:@" "];
NSLog(@"the sub %@",[[str1 objectAtIndex:0] stringByTrimmingCharactersInSet[NSCharacterSet whitespaceCharacterSet]]);
通过字符串是“X2.31”
NSString *strOrg = [NSString stringWithFormat:@"%@",@"SHMU=\"\" CODE=\"X2.31\" XTN=\""] ;
NSString *strLeft = [NSString stringWithFormat:@"%@",@"SHMU=\"\" CODE=\""] ;
NSString *strRight = [NSString stringWithFormat:@"%@",@"\" XTN=\""] ;
NSLog(@"%@", [self getDataBetweenString:strOrg LeftString:strLeft RightString:strRight LeftOffset:13]);
- (NSString *)getDataBetweenString:(NSString *)orgString LeftString:(NSString *)leftString RightString:(NSString *)rightString LeftOffset:(NSInteger)leftPos;
{
NSInteger left, right;
NSString *foundData;
NSScanner *scanner=[NSScanner scannerWithString:orgString];
[scanner scanUpToString:leftString intoString: nil];
left = [scanner scanLocation];
[scanner setScanLocation:left + leftPos];
[scanner scanUpToString:rightString intoString: nil];
right = [scanner scanLocation] + 1;
left += leftPos;
foundData = [orgString substringWithRange: NSMakeRange(left, (right - left) - 1)]; return foundData;
}
这仅特定于您发布的str 。您的号码后面必须跟第一个 X。
float f=[[str componentsSeparatedByString:@"X"][1] floatValue];