-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
  • 4,567
  • 13
  • 30
  • 40
Mukesh
  • 744
  • 6
  • 19

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
  • 14,770
  • 2
  • 37
  • 67
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
  • 510,973
  • 84
  • 1,183
  • 1,314