Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

objective c - Convert first number in an NSString into an Integer?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...