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

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

    Swift 4:

    extension String {
    
        /// the length of the string
        var length: Int {
            return self.characters.count
        }
    
        /// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
        ///
        /// - parameter index:  the start index
        /// - parameter length: the length of the substring
        ///
        /// - returns: the substring
        public func substring(index: Int, length: Int) -> String {
            if self.length <= index {
                return ""
            }
            let leftIndex = self.index(self.startIndex, offsetBy: index)
            if self.length <= index + length {
                return self.substring(from: leftIndex)
            }
            let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
            return self.substring(with: leftIndex.. "ABCDE".substring(left: 0, right: 2) -> "ABC"
        ///
        /// - parameter left:  the start index
        /// - parameter right: the end index
        ///
        /// - returns: the substring
        public func substring(left: Int, right: Int) -> String {
            if length <= left {
                return ""
            }
            let leftIndex = self.index(self.startIndex, offsetBy: left)
            if length <= right {
                return self.substring(from: leftIndex)
            }
            else {
                let rightIndex = self.index(self.endIndex, offsetBy: -self.length + right + 1)
                return self.substring(with: leftIndex..

    you can test it as follows:

        print("test: " + String("ABCDE".substring(index: 2, length: 3) == "CDE"))
        print("test: " + String("ABCDE".substring(index: 0, length: 3) == "ABC"))
        print("test: " + String("ABCDE".substring(index: 2, length: 1000) == "CDE"))
        print("test: " + String("ABCDE".substring(left: 0, right: 2) == "ABC"))
        print("test: " + String("ABCDE".substring(left: 1, right: 3) == "BCD"))
        print("test: " + String("ABCDE".substring(left: 3, right: 1000) == "DE"))
    

    Check https://gitlab.com/seriyvolk83/SwiftEx library. It contains these and other helpful methods.

提交回复
热议问题