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

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

    I've modified andrewz' post to make it compatible with Swift 2.0 (and maybe Swift 3.0). In my humble opinion, this extension is easier to understand and similar to what is available in other languages (like PHP).

    extension String {
    
        func length() -> Int {
            return self.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)
        }
        func substring(from:Int = 0, to:Int = -1) -> String {
           var nto=to
            if nto < 0 {
                nto = self.length() + nto
            }
            return self.substringWithRange(Range(
               start:self.startIndex.advancedBy(from),
               end:self.startIndex.advancedBy(nto+1)))
        }
        func substring(from:Int = 0, length:Int) -> String {
            return self.substringWithRange(Range(
                start:self.startIndex.advancedBy(from),
                end:self.startIndex.advancedBy(from+length)))
        }
    }
    

提交回复
热议问题