Index of a substring in a string with Swift

前端 未结 11 1648
自闭症患者
自闭症患者 2020-11-22 14:24

I\'m used to do this in JavaScript:

var domains = \"abcde\".substring(0, \"abcde\".indexOf(\"cd\")) // Returns \"ab\"

Swift doesn\'t have t

11条回答
  •  野性不改
    2020-11-22 14:44

    In Swift 4 :

    Getting Index of a character in a string :

    let str = "abcdefghabcd"
    if let index = str.index(of: "b") {
       print(index) // Index(_compoundOffset: 4, _cache: Swift.String.Index._Cache.character(1))
    }
    

    Creating SubString (prefix and suffix) from String using Swift 4:

    let str : String = "ilike"
    for i in 0...str.count {
        let index = str.index(str.startIndex, offsetBy: i) // String.Index
        let prefix = str[..

    Output

    prefix , suffix : ilike
    prefix i, suffix : like
    prefix il, suffix : ike
    prefix ili, suffix : ke
    prefix ilik, suffix : e
    prefix ilike, suffix : 
    

    If you want to generate a substring between 2 indices , use :

    let substring1 = string[startIndex...endIndex] // including endIndex
    let subString2 = string[startIndex..

提交回复
热议问题