@"text 932" のような NSString があります。
この文字列から数値を返す方法。数値は常に文字列の末尾にありますが、数値の長さが一定でないため、stringWithRange を使用できません。だから私はより良い方法を探しています。
また、この @"text 3232 text" のような文字列から数値を返す方法も知りたいです。番号の位置もわかりません。
文字列で数値を見つける関数はありますか?
これが両方の文字列で機能するソリューションです
NSString *myString = @"text 3232 text";
//Create a scanner with the string
NSScanner *scanner = [NSScanner scannerWithString:myString];
//Create a character set that includes all letters, whitespaces, and newlines
//These will be used as skip tokens
NSMutableCharacterSet *charactersToBeSkipped = [[NSMutableCharacterSet alloc]init];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[scanner setCharactersToBeSkipped:charactersToBeSkipped];
[charactersToBeSkipped release];
//Create an int to hold the number
int i;
//Do the work
if ([scanner scanInt:&i]) {
NSLog(@"i = %d", i);
}
の出力NSLog
は
i = 3232
小数を処理するには:
float f;
if ([scanner scanFloat:&f]) {
NSLog(@"f = %f", f);
}
更新:
一致があるかどうかをテストし、負数/10 進数を処理するように更新されました
NSString *inputString=@"text text -9876.234 text";
NSString *regExprString=@"-{0,1}\\d*\\.{0,1}\\d+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSRange rangeOfFirstMatch=[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range;
if(rangeOfFirstMatch.length>0){
NSString *firstMatch=[inputString substringWithRange:rangeOfFirstMatch];
NSLog(@"firstmatch:%@",firstMatch);
}
else{
NSLog(@"No Match");
}
オリジナル: 正規表現を使用したソリューションは次のとおりです。
NSString *inputString=@"text text 0123456 text";
NSString *regExprString=@"[0-9]+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSString *firstMatch=[inputString substringWithRange:[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range];
NSLog(@"%@",firstMatch);
出力: 0123456
そこから実際の整数が必要な場合は、次を追加できます。
NSInteger i=[firstMatch integerValue];
NSLog(@"%d",i);
出力は次のとおりです。123456