将字符串转换为 int

我无法把字符串转换成整数。我谷歌了一下,但我能找到的只有如何将整型数转换成字符串。有人知道反过来怎么做吗?谢谢。

131870 次浏览

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];
NSString *string = /* Assume this exists. */;
int value = [string intValue];

I use:

NSInteger stringToInt(NSString *string) {
return [string integerValue];
}

And vice versa:

NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:@"%d", integer];
}

See the NSString Class Reference.

NSString *string = @"5";
int value = [string intValue];

Very easy..

int (name of integer) = [(name of string, no ()) intValue];

Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.

You can also use like :

NSInteger getVal = [self.string integerValue];

This is the simple solution for converting string to int

NSString *strNum = @"10";
int num = [strNum intValue];

but when you are getting value from the textfield then,

int num = [txtField.text intValue];

where txtField is an outlet of UITextField

I had to do something like this but wanted to use a getter/setter for mine. In particular I wanted to return a long from a textfield. The other answers all worked well also, I just ended up adapting mine a little as my school project evolved.

long ms = [self.textfield.text longLongValue];
return ms;

Swift 3.0:

Int("5")

or

let stringToConvert = "5"
Int(stringToConvert)

To convert an String number to an Int, you should do this:

let stringNumber = "5"
let number = Int(stringNumber)