Convert a string into an int

后端 未结 11 2452
别跟我提以往
别跟我提以往 2020-12-04 14:51

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

相关标签:
11条回答
  • 2020-12-04 15:29

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

    let stringNumber = "5"
    let number = Int(stringNumber)
    
    0 讨论(0)
  • 2020-12-04 15:32

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

    0 讨论(0)
  • 2020-12-04 15:34

    I use:

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

    And vice versa:

    NSString* intToString(NSInteger integer) {
        return [NSString stringWithFormat:@"%d", integer];
    }
    
    0 讨论(0)
  • 2020-12-04 15:40

    How about

    [@"7" intValue];
    

    Additionally if you want an NSNumber you could do

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter numberFromString:@"7"];
    
    0 讨论(0)
  • 2020-12-04 15:41

    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

    0 讨论(0)
  • 2020-12-04 15:45

    See the NSString Class Reference.

    NSString *string = @"5";
    int value = [string intValue];
    
    0 讨论(0)
提交回复
热议问题