如何删除String Swift 3中的字符?

问题描述 投票:1回答:1

用于获取特定字符之前的字符串的代码:

let string = "Hello World"
if let range = string.range(of: "World") {
    let firstPart = string[string.startIndex..<range.lowerBound]
    print(firstPart) // print Hello
}

首先,我有一个程序将Hex float转换为Binary float,我想从Binary string answer中删除所有“0”直到第一个“1”。例:

enter image description here

有任何想法吗?

swift string
1个回答
6
投票

您可以使用正则表达式:

var str = "001110111001"
str = str.replacingOccurrences(of: "0", with: "", options: [.anchored], range: nil)

anchored选项意味着仅在字符串的开头搜索0s。

© www.soinside.com 2019 - 2024. All rights reserved.