在Swift中,如何将String转换为Int64?

时间:2022-09-02 09:12:08

I am loading in lines from a text file with very large numbers. String has the toInt method, but how do you convert a string to an Int64 which will be able to handle the large numbers?

我正在从具有非常大数字的文本文件中加载行。 String有toInt方法,但是如何将字符串转换为能够处理大数字的Int64呢?

I don't see a toInt64 method or a toLong etc. There must be a way, but I haven't found anything by searching yet.

我没有看到toInt64方法或toLong等。必须有办法,但我还没有通过搜索找到任何东西。

Alternatively I guess I could read the numbers in the string digit by digit (or by groups of digits) and then add them together with appropriate factors of ten, but that seems like overkill. Or maybe the proper way is to read the data in a binary form and convert it that way?

或者我想我可以用数字(或数字组)读取字符串中的数字,然后将它们与适当的因子10一起添加,但这似乎有点过分。或者正确的方法是以二进制形式读取数据并以这种方式转换它?

Thanks

谢谢

4 个解决方案

#1


18  

As of Swift 2.1.1 you can simply initialize Int64 with String

从Swift 2.1.1开始,您只需使用String初始化Int64即可

let number: Int64? = Int64("42")

#2


10  

If you don't mind using NSString, you can do this

如果您不介意使用NSString,则可以执行此操作

let str = "\(LLONG_MAX)"
let strAsNSString = str as NSString
let value = strAsNSString.longLongValue

Note that unlike toInt(), longLongValue will return 0 if the string is not a legal number whereas toInt() will return nil in that case.

请注意,与toInt()不同,如果字符串不是合法数字,longLongValue将返回0,而在这种情况下,toInt()将返回nil。

#3


1  

import Darwin
let str = ...
let i = strtoll(str, nil, 10)

#4


1  

import Darwin

let strBase10 = "9223372036854775807"
let i64FromBase10 = strtoll(strBase10, nil, 10)

let strBase16 = "0xFFFFFFFFFFFFFFFF"
let i64FromBase16 = strtoll(strBase16, nil, 16)

strtoll means STRingTOLongLong

strtoll意味着STRingTOLongLong

http://www.freebsd.org/cgi/man.cgi?query=strtoll

http://www.freebsd.org/cgi/man.cgi?query=strtoll

#1


18  

As of Swift 2.1.1 you can simply initialize Int64 with String

从Swift 2.1.1开始,您只需使用String初始化Int64即可

let number: Int64? = Int64("42")

#2


10  

If you don't mind using NSString, you can do this

如果您不介意使用NSString,则可以执行此操作

let str = "\(LLONG_MAX)"
let strAsNSString = str as NSString
let value = strAsNSString.longLongValue

Note that unlike toInt(), longLongValue will return 0 if the string is not a legal number whereas toInt() will return nil in that case.

请注意,与toInt()不同,如果字符串不是合法数字,longLongValue将返回0,而在这种情况下,toInt()将返回nil。

#3


1  

import Darwin
let str = ...
let i = strtoll(str, nil, 10)

#4


1  

import Darwin

let strBase10 = "9223372036854775807"
let i64FromBase10 = strtoll(strBase10, nil, 10)

let strBase16 = "0xFFFFFFFFFFFFFFFF"
let i64FromBase16 = strtoll(strBase16, nil, 16)

strtoll means STRingTOLongLong

strtoll意味着STRingTOLongLong

http://www.freebsd.org/cgi/man.cgi?query=strtoll

http://www.freebsd.org/cgi/man.cgi?query=strtoll