2013-03-21 100 views
0

獲取子我需要從字符串從響應的NSString

NSString *str = @"SHMU=\"\" CODE=\"X2.31\" XTN=\"; 

CODE的價值(X2.31)我如何能得到那個特定的子?

+4

您可以使用'NSScanner'或'NSRegularExpression ' – borrrden 2013-03-21 07:12:05

+0

它總是以這種格式編號,並且編號前面是X? – 2013-03-21 07:18:03

回答

0
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; 
} 
0

這只是具體海峽您發佈。 您的號碼必須跟一十

float f=[[str componentsSeparatedByString:@"X"][1] floatValue]; 
1

嘗試下面的一個

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」

+0

謝謝.....我需要從字符串CODE =得到子字符串CODE值(X2.31)在這個字符串中 NSString * str = @「SHMU = \」\「CODE = \」X2.31 \ 「XTN = \ LHNU = \」\「CODE = \」Z2.32 \「XTN = \ GHMU = \」\「CODE = \」L2.3 \「XTN = \」; 我怎麼能得到特定的子字符串? – VishnuVardhan 2013-03-21 09:27:31

+0

你可以給我笏字符串你再次獲得請編輯它在你的問題清晰或標記爲評論 – 2013-03-21 09:31:38