【问题标题】:How to split numeric and substring from main string in SWIFT?如何从 SWIFT 中的主字符串中拆分数字和子字符串?
【发布时间】:2020-09-10 15:43:15
【问题描述】:

我有一种情况,我需要将数值和其他子字符串与主给定字符串分开。

假设主字符串是350.55kph。 然后我想要的结果是 350.55 作为数值,kph 是其他子字符串。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: ios swift string substring numeric


    【解决方案1】:

    方法如下:

    let string = "350kph"
    let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
    for item in stringArray {
        if let integer = Int(item) {
            print("integer: \(integer)")
        }
    }
    

    注意:这适用于包含多个 Int 的字符串,例如:“350km per 2hr”。你只需要:

    let string = "350kph"
    let integer = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
    print("integer: \(integer)")
    

    好的,我看到了你的编辑,这是小数的方法,(还有其他方法):

    let string = "350.55kph"
    let components = string.components(separatedBy: ".")
    let decimalPart = Int(components.last!.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) ?? 0
    let double = Double("\(components.first ?? "0").\(decimalPart)")
    print(decimalPart,"double: \(double)")
    

    其他方式:你可以修改CharecterSet来达到想要的效果。

    【讨论】:

    • 刚刚对我的问题进行了编辑。这些值可以是任何浮点数或双精度值。 350.55 公里/小时。
    • @MaulikPandya 立即查看 ??
    【解决方案2】:

    正则表达式可能会起作用。 ([0-9.]+)([A-Za-z]+) 之类的东西会将其提取为两组:一组带有数字部分,另一组带有单位。

    这里有一些关于如何与这些组合作的选项:Swift 3 - How do I extract captured groups in regular expressions?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多