Swift: get index of start of a substring in a string [duplicate]
Asked Answered
P

1

2

Is there a way to search a string for the index of the start of a substring?

Like, "hello".indexOf("el") would return 1. Thanks

Phytoplankton answered 19/8, 2015 at 20:39 Comment(0)
B
1

You can reach using the rangeOfString function that finds and returns the range of the first occurrence of a given string within a given range like in the following way:

var text = "Hello Victor Sigler"

if let indexOf = text.rangeOfString("Victor")?.startIndex {
   println(indexOf) //6
}

I hope this help you.

Bribe answered 19/8, 2015 at 20:48 Comment(1)
In Swift 5 this throws a Type of expression is ambiguous without more context error for startIndex (tested in Playground).Trixie

© 2022 - 2024 — McMap. All rights reserved.