gpt4 book ai didi

ios - 从 NSString 返回数字

转载 作者:行者123 更新时间:2023-11-28 19:19:15 26 4
gpt4 key购买 nike

我有这样的 NSString:@"text 932"。

我如何从这个字符串中返回数字。数字总是在字符串的末尾,但我不能使用 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);
}

关于ios - 从 NSString 返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10262001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com