1

i'm trying to find the starting positions of a substring within a string. It's only returning the correct index if it's just characters without any emoji. However, when special characters like emojis are used, the returned index is not correct. I want to count each emoji or character as one character. Here is my code:

extension String {
    func index(of string: String, options: CompareOptions = .literal) -> Index? {
        return range(of: string, options: options)?.lowerBound
    }
    func indexes(of string: String, options: CompareOptions = .literal) -> [Index] {
        var result: [Index] = []
        var start = startIndex
        while let range = range(of: string, options: options, range: start..<endIndex) {
            result.append(range.lowerBound)
            start = range.upperBound
        }
        return result
    }
}

Any suggestions? Thanks!

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
mei02
  • 61
  • 1
  • 4
  • Compare http://stackoverflow.com/questions/39104152/how-to-know-if-two-emojis-will-be-displayed-as-one-emoji – Martin R Apr 14 '17 at 14:18
  • What results do do get and what do you expect? A concrete example would be helpful. – Martin R Apr 14 '17 at 14:34
  • for example: ".. lol" index start of lol is 3. But if i replace for example the ".." by a laughing face emoji, i get a 5 index starting position of lol. – mei02 Apr 14 '17 at 14:39
  • Thanks Leo for your answer but that still doesn't solve the issue! – mei02 Apr 14 '17 at 14:58
  • @mei02 I didn't answer only removed the unnecessary code – Leo Dabus Apr 14 '17 at 15:26
  • @mei02: The return value is a `String.Index` and the result is exactly what you need when indexing another string. If you want the count the distance in characters then compute `distance(from: startIndex, to: range.lowerBound)` – Martin R Apr 14 '17 at 15:33
  • thank you @MartinR for your answer! I have a question. When making an NSRange it needs a location as a parameter but this location doesn't take the emoji as one character. Any possible solution for that? – mei02 Apr 14 '17 at 16:29

0 Answers0