Index of a substring in a string with Swift -


i'm used in javascript:

var domains = "abcde".substring(0, "abcde".indexof("cd")) // returns "ab" 

swift doesn't have function, how similar?

xcode 8.3.1 • swift 3.1

extension string {     func index(of string: string, options: compareoptions = .literal) -> index? {         return range(of: string, options: options)?.lowerbound     }     func endindex(of string: string, options: compareoptions = .literal) -> index? {         return range(of: string, options: options)?.upperbound     }     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     }     func ranges(of string: string, options: compareoptions = .literal) -> [range<index>] {         var result: [range<index>] = []         var start = startindex         while let range = range(of: string, options: options, range: start..<endindex) {             result.append(range)             start = range.upperbound         }         return result     } } 

usage:

let str = "abcde" if let index = str.index(of: "cd") {     let domains = str.prefix(upto: index)     print(domains)  // "ab\n" } 

let str = "hello, playground, playground, playground" str.index(of: "play")      // 7 str.endindex(of: "play")   // 11 str.indexes(of: "play")    // [7, 19, 31] str.ranges(of: "play")     // [{lowerbound 7, upperbound 11}, {lowerbound 19, upperbound 23}, {lowerbound 31, upperbound 35}] 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -