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

前端 未结 22 837
感情败类
感情败类 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:06

    The one thing that adds clatter is the repeated stringVar:

    stringVar[stringVar.index(stringVar.startIndex, offsetBy: ...)

    In Swift 4

    An extension can reduce some of that:

    extension String {
    
        func index(at location: Int) -> String.Index {
            return self.index(self.startIndex, offsetBy: location)
        }
    }
    

    Then, usage:

    let string = "abcde"
    
    let to = string[..

    It should be noted that to and from are type Substring (or String.SubSequance). They do not allocate new strings and are more efficient for processing.

    To get back a String type, Substring needs to be casted back to String:

    let backToString = String(from)
    

    This is where a string is finally allocated.

提交回复
热议问题