objective-c 将字符串转换为 int-objective c
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18505143/
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 string to int-objective c
提问by DonyorM
I haven't been able to figure out how to convert a NSString to an int. I'm trying to convert ASCII to text, but to do that I need to convert a string to an int.
我一直无法弄清楚如何将 NSString 转换为 int。我正在尝试将 ASCII 转换为文本,但为此我需要将字符串转换为 int。
I find it really strange that this isn't anywhere online or in stack overflow. I'm sure I'm not the online one who needs this.
我觉得这不是在线或堆栈溢出的任何地方,这真的很奇怪。我确定我不是需要这个的在线人。
Thanks in advance for helping.
提前感谢您的帮助。
P.S. If this helps here is the code I'm using to convert to ASCII:
PS 如果这有帮助,这里是我用来转换为 ASCII 的代码:
+ (NSString *) decodeText:(NSString *)text {
NSArray * asciiCode = [text componentsSeparatedByString:@"|"];
int i = 0;
NSMutableString *decoded;
while (i < ([asciiCode count]-1) ) {
NSString *toCode = [asciiCode objectAtIndex:i];
int codeInt = toCode;
NSString *decode = [NSString stringWithFormat:@"%c", codeInt];
[decoded appendString:decode];
}
return decoded;
}
回答by User 1531343
To parse string to integer you should do:
要将字符串解析为整数,您应该执行以下操作:
NSString *a = @"123abc";
NSInteger b = [a integerValue];
回答by John Parker
Perhaps fractionally off-topic, but to convert to ASCII you could just use:
也许有点离题,但要转换为 ASCII,您可以使用:
[NSString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]
Or in your example:
或者在你的例子中:
return [text dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
This will return an NSData which you could iterate through to obtain a string representation of ASCII (s per your method) if this is what you require.
这将返回一个 NSData,如果这是您需要的,您可以遍历它以获得 ASCII 的字符串表示(根据您的方法)。
The reason for using this approach is because NSString's can store non-ASCII characters, you will of course potentially lose detail, but enabling the allowLossyConversion flag will attempt to overcome this. As per the Apple documentation:
使用这种方法的原因是因为 NSString 可以存储非 ASCII 字符,您当然可能会丢失细节,但启用 allowLossyConversion 标志将尝试克服这一点。根据Apple 文档:
For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘á' becomes ‘A', losing the accent.
例如,在将字符从 NSUnicodeStringEncoding 转换为 NSASCIIStringEncoding 时,字符 'á' 变成了 'A',失去了重音。

