Question:

I have an NSString like so:

@"200hello" 

or

@"0 something" 

What I would like to be able to do is take the first occuring number in the NSString and convert it into an int.

So that @"200hello" would become int = 200.

and @"0 something" would become int = 0.

Answer1:

int value; 
BOOL success =[[NSScanner scannerWithString:@"1000safkaj"] scanInteger:&value]; 

If the number is not always at the beginning:

NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet]; 
int value =[[@"adfsdg1000safkaj" stringByTrimmingCharactersInSet:nonDigits] intValue]; 

Answer2:

If the int value is always at the beginning of the string, you can simply use intValue.

NSString*string=@"123hello"; 
int myInt =[string intValue]; 

相关文章:

  • 2022-03-07
  • 2022-12-23
  • 2022-12-23
  • 2021-12-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案