如何在Swift 4中使用字符串切片下标?

时间:2017-08-08 08:04:27

标签: swift swift4

我有以下用Swift 3编写的简单代码:

let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)

从Xcode 9 beta 5,我收到以下警告:

  

'substring(to:)'已被弃用:请使用String切片下标和'partial range from'运算符。

如何在Swift 4中使用切片下标部分范围

19 个答案:

答案 0 :(得分:327)

你应该将一方留空,因此名称为"部分范围"。

let newStr = str[..<index]

同样代表部分范围来自运算符,只是将另一方留空:

let newStr = str[index...]

请注意,这些范围运算符会返回Substring。如果要将其转换为字符串,请使用String的初始化函数:

let newStr = String(str[..<index])

您可以阅读有关新子字符串here的更多信息。

答案 1 :(得分:229)

将子串(Swift 3)转换为字符串切片(Swift 4)

示例在Swift 3,4中:

let newStr = str.substring(to: index) // Swift 3
let newStr = String(str[..<index]) // Swift 4
let newStr = str.substring(from: index) // Swift 3
let newStr = String(str[index...]) // Swift 4 
let range = firstIndex..<secondIndex // If you have a range
let newStr = = str.substring(with: range) // Swift 3
let newStr = String(str[range])  // Swift 4

答案 2 :(得分:55)

Swift 4

用法

let text = "Hello world"
text[...3] // "Hell"
text[6..<text.count] // world
text[NSRange(location: 6, length: 3)] // wor

代码

import Foundation

extension String {
    subscript(value: NSRange) -> Substring {
        return self[value.lowerBound..<value.upperBound]
    }
}

extension String {
    subscript(value: CountableClosedRange<Int>) -> Substring {
        get {
            return self[index(at: value.lowerBound)...index(at: value.upperBound)]
        }
    }

    subscript(value: CountableRange<Int>) -> Substring {
        get {
            return self[index(at: value.lowerBound)..<index(at: value.upperBound)]
        }
    }

    subscript(value: PartialRangeUpTo<Int>) -> Substring {
        get {
            return self[..<index(at: value.upperBound)]
        }
    }

    subscript(value: PartialRangeThrough<Int>) -> Substring {
        get {
            return self[...index(at: value.upperBound)]
        }
    }

    subscript(value: PartialRangeFrom<Int>) -> Substring {
        get {
            return self[index(at: value.lowerBound)...]
        }
    }

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

答案 3 :(得分:27)

Swift 4更短:

var string = "123456"
string = String(string.prefix(3)) //"123"
string = String(string.suffix(3)) //"456"

答案 4 :(得分:23)

将代码转换为Swift 4也可以这样做:

let str = "Hello, playground"
let index = str.index(of: ",")!
let substr = str.prefix(upTo: index)

您可以使用以下代码获得新字符串:

let newString = String(str.prefix(upTo: index))

答案 5 :(得分:13)

substring(from:index) 转换为 [index ...]

检查样本

let text = "1234567890"
let index = text.index(text.startIndex, offsetBy: 3)

text.substring(from: index) // "4567890"   [Swift 3]
String(text[index...])      // "4567890"   [Swift 4]

答案 6 :(得分:8)

Swift4:

extension String {
    func subString(from: Int, to: Int) -> String {
       let startIndex = self.index(self.startIndex, offsetBy: from)
       let endIndex = self.index(self.startIndex, offsetBy: to)
       return String(self[startIndex...endIndex])
    }
}

用法:

var str = "Hello, playground"
print(str.subString(from:1,to:8))

答案 7 :(得分:7)

一些有用的扩展:

extension String {
    func substring(from: Int, to: Int) -> String {
        let start = index(startIndex, offsetBy: from)
        let end = index(start, offsetBy: to - from)
        return String(self[start ..< end])
    }

    func substring(range: NSRange) -> String {
        return substring(from: range.lowerBound, to: range.upperBound)
    }
}

答案 8 :(得分:6)

Swift3和Swift4中uppercasedFirstCharacter便利属性的示例。

Property uppercasedFirstCharacterNew演示了如何在Swift4中使用String切片下标。

extension String {

   public var uppercasedFirstCharacterOld: String {
      if characters.count > 0 {
         let splitIndex = index(after: startIndex)
         let firstCharacter = substring(to: splitIndex).uppercased()
         let sentence = substring(from: splitIndex)
         return firstCharacter + sentence
      } else {
         return self
      }
   }

   public var uppercasedFirstCharacterNew: String {
      if characters.count > 0 {
         let splitIndex = index(after: startIndex)
         let firstCharacter = self[..<splitIndex].uppercased()
         let sentence = self[splitIndex...]
         return firstCharacter + sentence
      } else {
         return self
      }
   }
}

let lorem = "lorem".uppercasedFirstCharacterOld
print(lorem) // Prints "Lorem"

let ipsum = "ipsum".uppercasedFirstCharacterNew
print(ipsum) // Prints "Ipsum"

答案 9 :(得分:5)

使用Swift 4从创建SubString(前缀和后缀):

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

输出

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix : 

如果要生成2个索引之间的子字符串,请使用:

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

答案 10 :(得分:5)

您可以使用类String的扩展名创建自定义subString方法,如下所示:

extension String {
    func subString(startIndex: Int, endIndex: Int) -> String {
        let end = (endIndex - self.count) + 1
        let indexStartOfText = self.index(self.startIndex, offsetBy: startIndex)
        let indexEndOfText = self.index(self.endIndex, offsetBy: end)
        let substring = self[indexStartOfText..<indexEndOfText]
        return String(substring)
    }
}

答案 11 :(得分:4)

我已经编写了一个字符串扩展名来替换'String:subString:'

extension String {

    func sliceByCharacter(from: Character, to: Character) -> String? {
        let fromIndex = self.index(self.index(of: from)!, offsetBy: 1)
        let toIndex = self.index(self.index(of: to)!, offsetBy: -1)
        return String(self[fromIndex...toIndex])
    }

    func sliceByString(from:String, to:String) -> String? {
        //From - startIndex
        var range = self.range(of: from)
        let subString = String(self[range!.upperBound...])

        //To - endIndex
        range = subString.range(of: to)
        return String(subString[..<range!.lowerBound])
    }

}
  

用法:"Date(1511508780012+0530)".sliceByString(from: "(", to: "+")

     

Example Result:“1511508780012”

PS:Optionals被迫解包。请在必要时添加类型安全检查。

答案 12 :(得分:2)

这是我的解决方案,没有警告,没有错误,但完美

let redStr: String = String(trimmStr[String.Index.init(encodedOffset: 0)..<String.Index.init(encodedOffset: 2)])
let greenStr: String = String(trimmStr[String.Index.init(encodedOffset: 3)..<String.Index.init(encodedOffset: 4)])
let blueStr: String = String(trimmStr[String.Index.init(encodedOffset: 5)..<String.Index.init(encodedOffset: 6)])

答案 13 :(得分:2)

使用此方法,您可以获得特定范围的字符串。您需要传递开始索引,然后传递所需的字符总数。

extension String{
    func substring(fromIndex : Int,count : Int) -> String{
        let startIndex = self.index(self.startIndex, offsetBy: fromIndex)
        let endIndex = self.index(self.startIndex, offsetBy: fromIndex + count)
        let range = startIndex..<endIndex
        return String(self[range])
    }
}

答案 14 :(得分:2)

编程时,我经常使用简单的A-Za-z和0-9字符串。无需困难的索引操作。此扩展程序基于普通的左/中/右功能。

extension String {

    // LEFT
    // Returns the specified number of chars from the left of the string
    // let str = "Hello"
    // print(str.left(3))         // Hel
    func left(_ to: Int) -> String {
        return "\(self[..<self.index(startIndex, offsetBy: to)])"
    }

    // RIGHT
    // Returns the specified number of chars from the right of the string
    // let str = "Hello"
    // print(str.left(3))         // llo
    func right(_ from: Int) -> String {
        return "\(self[self.index(startIndex, offsetBy: self.length-from)...])"
    }

    // MID
    // Returns the specified number of chars from the startpoint of the string
    // let str = "Hello"
    // print(str.left(2,amount: 2))         // ll
    func mid(_ from: Int, amount: Int) -> String {
        let x = "\(self[self.index(startIndex, offsetBy: from)...])"
        return x.left(amount)
    }
}

答案 15 :(得分:1)

如果你只是想得到一个特定字符的子串,你不需要先找到索引,你可以使用prefix(while:)方法

let str = "Hello, playground"
let subString = str.prefix { $0 != "," } // "Hello" as a String.SubSequence

答案 16 :(得分:0)

希望这会有所帮助: -

var string = "123456789"

如果你想要一个特定索引之后的子字符串。

var indexStart  =  string.index(after: string.startIndex )// you can use any index in place of startIndex
var strIndexStart   = String (string[indexStart...])//23456789

如果你想在最后删除一些字符串后想要一个子字符串。

var indexEnd  =  string.index(before: string.endIndex)
var strIndexEnd   = String (string[..<indexEnd])//12345678

您还可以使用以下代码创建索引: -

var  indexWithOffset =  string.index(string.startIndex, offsetBy: 4)

答案 17 :(得分:0)

希望它会有所帮助。

extension String {
    func getSubString(_ char: Character) -> String {
        var subString = ""
        for eachChar in self {
            if eachChar == char {
                return subString
            } else {
                subString += String(eachChar)
            }
        }
        return subString
    }
}


let str: String = "Hello, playground"
print(str.getSubString(","))

答案 18 :(得分:0)

`var str =“你好,操场”

let indexcut = str.firstIndex(of:“,”)

print(String(str[..<indexcut!]))

print(String(str[indexcut!...])) `

您可以通过这种方式尝试并获得正确的结果