ios 将字符串转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6638085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a string into an int
提问by MacN00b
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.
我在将字符串转换为整数时遇到问题。我用谷歌搜索,但我能找到的只是如何将 int 转换为字符串。有谁知道如何反其道而行之?谢谢。
回答by Espresso
See the NSString Class Reference.
请参阅NSString 类参考。
NSString *string = @"5";
int value = [string intValue];
回答by Paul.s
How about
怎么样
[@"7" intValue];
Additionally if you want an NSNumber
you could do
另外,如果你想要一个NSNumber
你可以做的
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];
回答by max_
I use:
我用:
NSInteger stringToInt(NSString *string) {
return [string integerValue];
}
And vice versa:
反之亦然:
NSString* intToString(NSInteger integer) {
return [NSString stringWithFormat:@"%d", integer];
}
回答by Josh O'Connor
Swift 3.0:
斯威夫特 3.0:
Int("5")
or
或者
let stringToConvert = "5"
Int(stringToConvert)
回答by iAnkit
This is the simple solution for converting string to int
这是将字符串转换为 int 的简单解决方案
NSString *strNum = @"10";
int num = [strNum intValue];
but when you are getting value from the textfieldthen,
但是当你从文本字段中获取价值时,
int num = [txtField.text intValue];
where txtFieldis an outlet of UITextField
其中txtField是UITextField的出口
回答by natur3
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.
我不得不做这样的事情,但想为我的使用 getter/setter。特别是我想从文本字段返回一个 long 。其他答案也都很好,随着我的学校项目的发展,我最终稍微调整了我的答案。
long ms = [self.textfield.text longLongValue];
return ms;
回答by Alexsander Akers
NSString *string = /* Assume this exists. */;
int value = [string intValue];
回答by Jacob
Very easy..
好简单..
int (name of integer) = [(name of string, no ()) intValue];
int (name of integer) = [(name of string, no ()) intValue];
回答by dotslashlu
Yet another way: if you are working with a C string, e.g. const char *, C native atoi()
is more convenient.
另一种方式:如果您正在使用 C 字符串,例如 const char *,C 本机atoi()
更方便。
回答by newbee
You can also use like :
你也可以使用像:
NSInteger getVal = [self.string integerValue];
NSInteger getVal = [self.string integerValue];