在Swift中,如何将String转换为Int作为base 2,虽然像Java中的Long.parseLong一样基础36?

时间:2014-11-09 01:41:48

标签: ios swift

如何在Swift中将字符串转换为Long?

在Java中我会做Long.parseLong("str", Character.MAX_RADIX)

4 个答案:

答案 0 :(得分:3)

如上所述here,您可以使用标准库函数strtoul():

let base36 = "1ARZ"
let number = strtoul(base36, nil, 36)
println(number) // Output: 60623

第三个参数是基数。有关函数如何处理空格和其他详细信息,请参阅man page

答案 1 :(得分:0)

这是Swift中的parseLong()。请注意,该函数返回Int?(可选Int),必须将其解包以供使用。

// Function to convert a String to an Int?.  It returns nil
// if the string contains characters that are not valid digits
// in the base or if the number is too big to fit in an Int.

func parseLong(string: String, base: Int) -> Int? {
    let digits = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    var number = 0
    for char in string.uppercaseString {
        if let digit = find(digits, char) {
            if digit < base {
                // Compute the value of the number so far
                // allowing for overflow
                let newnumber = number &* base &+ digit

                // Check for overflow and return nil if
                // it did overflow
                if newnumber < number {
                    return nil
                }
                number = newnumber
            } else {
                // Invalid digit for the base
                return nil
            }
        } else {
            // Invalid character not in digits
            return nil
        }
    }
    return number
}

if let result = parseLong("1110", 2) {
    println("1110 in base 2 is \(result)")  // "1110 in base 2 is 14"
}

if let result = parseLong("ZZ", 36) {
    println("ZZ in base 36 is \(result)")   // "ZZ in base 36 is 1295"
}

答案 2 :(得分:0)

我们现在在Swift标准库中内置了以下转换功能:

使用2到36为底进行编码:https://developer.apple.com/documentation/swift/string/2997127-init 使用2到36底进行解码:https://developer.apple.com/documentation/swift/int/2924481-init

答案 3 :(得分:-3)

迅捷的方式:

"123".toInt() // Return an optional

C方式:

atol("1232")

或者使用NSString的integerValue方法

("123" as NSString).integerValue