1

This is a bit on an odd ball question and I am not sure if it is possible to do, none the less.

I am trying to identify the "count" position of an item within a string.

For instance if I have a string: "hello what a lovely day" (23 characters) and I would like to know where in the sting the spaces are. In this case the sting would have a space at the 6th, 11th, 13th and 20th characters. Is there a function that would provide this feedback?

Any insight would be appreciated.

Thank you in advance for your valued time and insight.

1 Answers1

4

Try this extension:

extension String {
    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex
        
        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }
        
        return indices
    }
}

Usage (note that in Swift, nth characters start at 0 and not 1):

let string = "hello what a lovely day"
let indices = string.indicesOf(string: " ")
print("Indices are \(indices)")

Indices are [5, 10, 12, 19]

aheze
  • 24,434
  • 8
  • 68
  • 125
  • 2
    I have this extension buried in my app, and I think it was from Stack Overflow, but I forgot who the original author is. I hope it's ok if I make the answer under community wiki. – aheze Jun 21 '21 at 02:18
  • 1
    That is absolutely incredible man!! And what an amazing response time too!! As soon as the time count down is done I will "check" as correct answer. Thank you. – Michael Szabo Jun 21 '21 at 02:22
  • 2
    @MichaelSzabo you might be interest in those posts as well https://stackoverflow.com/a/32306142/2303865 and https://stackoverflow.com/a/34540310/2303865 – Leo Dabus Jun 21 '21 at 02:47
  • 2
    @LeoDabus thank you Leo, I'm just now starting to get a grasp of extensions. Really excited about the potential functionality. Thanks for the additional resources!! – Michael Szabo Jun 21 '21 at 17:21