Swift: How to get substring from start to last index of character

前端 未结 22 843
感情败类
感情败类 2020-11-30 19:09

I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.

22条回答
  •  被撕碎了的回忆
    2020-11-30 19:43

    In Swift 5

    We need String.Index instead of simple Int value to represent Index.

    Also remember, when we try to get subString from Swift String (value type), we actually have to iterate with Sequence protocol, which returns String.SubSequence type instead of String type.

    To get back String from String.SubSequence, use String(subString)

    Example As Below:

        let string = "https://stackoverflow.com"
        let firstIndex = String.Index(utf16Offset: 0, in: string)
        let lastIndex = String.Index(utf16Offset: 6, in: string)
        let subString = String(string[firstIndex...lastIndex])
    

提交回复
热议问题