-6

I have a string (asderwt.qwertyu.zxcvbbnnhg) and I want to change it to .qwertyu.zxcvbbnnhg.

I have tried to do this using the following code:

Var str = "asderwt.qwertyu.zxcvbbnnhg"
if let dotRange = str.range(of: ".") {
str.removeSubrange(dotRange.lowerBound..<str.startIndex)
print("AAAAAAAAAA: \(str)")

 }
double-beep
  • 5,031
  • 17
  • 33
  • 41
Mukesh
  • 777
  • 7
  • 20

2 Answers2

2

Get the first index of the dot and get the substring after that index

let str = "asderwt.qwertyu.zxcvbbnnhg"
if let index = str.firstIndex(where: { $0 == "." }) {
    print(str[index...])//.qwertyu.zxcvbbnnhg
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
1

You are on the right track, but here

str.removeSubrange(dotRange.lowerBound..<str.startIndex)

the range bounds are in the wrong order. It should be

var str = "asderwt.qwertyu.zxcvbbnnhg"
if let dotRange = str.range(of: ".") {
    str.removeSubrange(str.startIndex..<dotRange.lowerBound) // <-- HERE
    print("Result: \(str)") // Result: .qwertyu.zxcvbbnnhg
}

You can also use a “partial range”

if let dotRange = str.range(of: ".") {
    str.removeSubrange(..<dotRange.lowerBound)
    print("Result: \(str)") // Result: .qwertyu.zxcvbbnnhg
}

Or with firstIndex(of:) instead of range(of:):

if let dotIndex = str.firstIndex(of: ".") {
    str.removeSubrange(..<dotIndex)
    print("Result: \(str)") // Result: .qwertyu.zxcvbbnnhg
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382