0

In swift 4 you can use the following method to extract a substring:

let str = "abcdefghci"
let index = str.index(of: "c") ?? str.endIndex
print(str[...index])

This will print abc

But how can I find the index of the last c, to extract a substring from that location ?

UPDATE
@vadian please see the attached image:

enter image description here

nshathish
  • 417
  • 8
  • 23

1 Answers1

5

Use range(of which can search backwards and use lowerBound as end index.

let str = "abcdefghci"
if let range = str.range(of: "c", options: .backwards)  {
    print(str[...range.lowerBound])
}
vadian
  • 274,689
  • 30
  • 353
  • 361