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

前端 未结 22 803
感情败类
感情败类 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 20:05

    String has builtin substring feature:

    extension String : Sliceable {
        subscript (subRange: Range) -> String { get }
    }
    

    If what you want is "going to the first index of a character", you can get the substring using builtin find() function:

    var str = "www.stackexchange.com"
    str[str.startIndex ..< find(str, ".")!] // -> "www"
    

    To find last index, we can implement findLast().

    /// Returns the last index where `value` appears in `domain` or `nil` if
    /// `value` is not found.
    ///
    /// Complexity: O(\ `countElements(domain)`\ )
    func findLast(domain: C, value: C.Generator.Element) -> C.Index? {
        var last:C.Index? = nil
        for i in domain.startIndex..

    ADDED:

    Maybe, BidirectionalIndexType specialized version of findLast is faster:

    func findLast(domain: C, value: C.Generator.Element) -> C.Index? {
        for i in lazy(domain.startIndex ..< domain.endIndex).reverse() {
            if domain[i] == value {
                return i
            }
        }
        return nil
    }
    

提交回复
热议问题