1

Code to get the string before a certain character:

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

To begin with, I have a program that converts Hex float to a Binary float and I want to remove all "0" from Binary string answer until first "1". Example:

enter image description here

Any ideas?

Hamish
  • 78,605
  • 19
  • 187
  • 280
DanielD
  • 87
  • 1
  • 5
  • possible duplicate of https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string – swetansh kumar Nov 13 '17 at 12:50
  • 3
    Here is a way of converting that won't create the leading 0's in the first place: https://stackoverflow.com/a/36967037/1630618 . In your case `String(Int("3b9", radix: 16)!, radix: 2)` – vacawama Nov 13 '17 at 12:58

1 Answers1

6

You can use Regular Expression:

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

The anchored option means search for 0s at the start of the string only.

Code Different
  • 90,614
  • 16
  • 144
  • 163