如何在Swift中將字符串轉換爲長整型?在Swift中,如何將String轉換爲Int作爲基礎2,儘管基礎36像Java中的Long.parseLong一樣?
在Java中我會做Long.parseLong("str", Character.MAX_RADIX)
。
如何在Swift中將字符串轉換爲長整型?在Swift中,如何將String轉換爲Int作爲基礎2,儘管基礎36像Java中的Long.parseLong一樣?
在Java中我會做Long.parseLong("str", Character.MAX_RADIX)
。
斯威夫特方式:
"123".toInt() // Return an optional
Ç方式:
atol("1232")
或者使用的NSString的integerValue方法
("123" as NSString).integerValue
這裏是斯威夫特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("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
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"
}
感謝您的回答!但是我發現了一個標準庫函數strtoul()來實現這種情況 – 2014-11-10 14:22:55
你想寫在Java或Swift? – Shuo 2014-11-09 01:45:15
@Shuo他已經提供了Java代碼,所以他的意思是Swift。 – August 2014-11-09 01:48:07
我想寫在Swift! – 2014-11-09 01:51:11