Convert a string into an int

IosObjective CXcodeIos4

Ios Problem Overview


I'm having trouble converting a string into an integer. I googled it but all I can find is how to convert an int into a string. Does anyone know how to do it the other way around? Thanks.

Ios Solutions


Solution 1 - Ios

See the NSString Class Reference.

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

Solution 2 - Ios

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];

Solution 3 - Ios

I use:

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

And vice versa:

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

Solution 4 - Ios

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

Solution 5 - Ios

Swift 3.0:

Int("5")

or

let stringToConvert = "5"
Int(stringToConvert)

Solution 6 - Ios

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;

Solution 7 - Ios

NSString *string = /* Assume this exists. */;
int value = [string intValue];

Solution 8 - Ios

Very easy..

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

Solution 9 - Ios

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

Solution 10 - Ios

You can also use like :

NSInteger getVal = [self.string integerValue];

Solution 11 - Ios

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMacN00bView Question on Stackoverflow
Solution 1 - IosEspressoView Answer on Stackoverflow
Solution 2 - IosPaul.sView Answer on Stackoverflow
Solution 3 - Iosmax_View Answer on Stackoverflow
Solution 4 - IosiAnkitView Answer on Stackoverflow
Solution 5 - IosJosh O'ConnorView Answer on Stackoverflow
Solution 6 - Iosnatur3View Answer on Stackoverflow
Solution 7 - IosAlexsander AkersView Answer on Stackoverflow
Solution 8 - IosJacobView Answer on Stackoverflow
Solution 9 - IosdotslashluView Answer on Stackoverflow
Solution 10 - IosnewbeeView Answer on Stackoverflow
Solution 11 - IosAle MohamadView Answer on Stackoverflow