gpt4 book ai didi

ios - NSNumberFormatter、numberFromString 及其行为

转载 作者:行者123 更新时间:2023-11-29 01:38:31 24 4
gpt4 key购买 nike

我想问一下这是否是 NSNumberFormatter 应该有的行为。假设我有一个 String,但数字不完整,例如:123809d 328190 jdksla。为什么当我使用 numberFromString 时,我得到的是 nil 而不是数字?(顺便说一句,我确实在末尾包含了 intValue 或 doubleValue)。这不是 NSNumberFormatter 应该如何工作,或者您必须将数字 100% 地转换为字符串才能正常工作吗?这是上面的代码:

import UIKit

let p = "123809d328190jdksla"
let k = NSNumberFormatter().numberFromString(p)?.doubleValue



k = nil

最佳答案

这是一种方法:

// First, here's the string
let mixedString = "123809d328190jdksla"

// For convenience let's define the charaterset of all non-numeric characters.
// We do this by inverting the numeric character set.
let nonDecimalCharacterSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet

// Now the meat of the method
let numericStrings = mixedString
.componentsSeparatedByCharactersInSet(nonDecimalCharacterSet) // 1
.filter { !($0.isEmpty) } // 2
.reduce("", combine: +) // 3

// 1 Split the string into an array of strings by non-decimal characters
// 2 remove empty strings
// 3 combine the array of strings into a single string

// Now turn the string into a number
let number = Int(numericString)

您可以将所有这些放到一个 playground 中,看看它是如何工作的。 enter image description here

关于ios - NSNumberFormatter、numberFromString 及其行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com