Index of a substring in a string with Swift

前端 未结 11 1550
自闭症患者
自闭症患者 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:50

    Using String[Range] subscript you can get the sub string. You need starting index and last index to create the range and you can do it as below

    let str = "abcde"
    if let range = str.range(of: "cd") {
      let substring = str[..

    If you don't define the start index this operator ..< , it take the starting index. You can also use str[str.startIndex.. instead of str[..

提交回复
热议问题