我有以下简单的代码写在Swift 3:
let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)
在Xcode 9 beta 5中,我得到了以下警告:
'substring(to:)'已弃用:请使用带有'partial range from'操作符的字符串切片下标。
这个部分范围的切片下标如何在Swift 4中使用?
我有以下简单的代码写在Swift 3:
let str = "Hello, playground"
let index = str.index(of: ",")!
let newStr = str.substring(to: index)
在Xcode 9 beta 5中,我得到了以下警告:
'substring(to:)'已弃用:请使用带有'partial range from'操作符的字符串切片下标。
这个部分范围的切片下标如何在Swift 4中使用?
你应该让一侧为空,因此被称为“部分范围”。
let newStr = str[..<index]
同样适用于操作符的部分范围,只需要将另一侧留空即可:
let newStr = str[index...]
请记住,这些范围操作符返回一个Substring。如果你想把它转换成一个字符串,使用string的初始化函数:
let newStr = String(str[..<index])
您可以在这里阅读更多关于新子字符串的信息。
Swift3和Swift4中的uppercasedFirstCharacter便利属性示例。
属性uppercasedFirstCharacterNew演示了如何在Swift4中使用字符串切片下标。
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"
你的代码转换到Swift 4也可以这样做:
let str = "Hello, playground"
let index = str.index(of: ",")!
let substr = str.prefix(upTo: index)
你可以使用下面的代码来创建一个新的字符串:
let newString = String(str.prefix(upTo: index))
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]
一些有用的扩展:
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)
}
}
转换子字符串(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
Swift 5,4
使用
let text = "Hello world"
text[0] // H
text[...3] // "Hell"
text[6..<text.count] // world
text[NSRange(location: 6, length: 3)] // wor
Code
import Foundation
public extension String {
subscript(value: Int) -> Character {
self[index(at: value)]
}
}
public extension String {
subscript(value: NSRange) -> Substring {
self[value.lowerBound..<value.upperBound]
}
}
public extension String {
subscript(value: CountableClosedRange<Int>) -> Substring {
self[index(at: value.lowerBound)...index(at: value.upperBound)]
}
subscript(value: CountableRange<Int>) -> Substring {
self[index(at: value.lowerBound)..<index(at: value.upperBound)]
}
subscript(value: PartialRangeUpTo<Int>) -> Substring {
self[..<index(at: value.upperBound)]
}
subscript(value: PartialRangeThrough<Int>) -> Substring {
self[...index(at: value.upperBound)]
}
subscript(value: PartialRangeFrom<Int>) -> Substring {
self[index(at: value.lowerBound)...]
}
}
private extension String {
func index(at offset: Int) -> String.Index {
index(startIndex, offsetBy: offset)
}
}
编程时,我经常用简单的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)
}
}
这就是我的解,没有警告,没有错误,但很完美
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)])
我写了一个字符串扩展替换' 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])
}
}
用法:“日期(1511508780012+0530)”sliceByString(from: "(", to: "+") 示例结果:"1511508780012"
PS:可选选项被强制展开。如有需要,请添加类型安全检查。
使用Swift 4从字符串创建子字符串(前缀和后缀):
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 :
如果你想在两个索引之间生成一个子字符串,使用:
let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex
你可以使用扩展类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)
}
}
希望这将帮助更多:-
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)
Swift 4/5更短:
let string = "123456"
let firstThree = String(string.prefix(3)) //"123"
let lastThree = String(string.suffix(3)) //"456"
用这个方法你可以得到字符串的特定范围。你需要传递起始索引和你想要的字符总数。
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])
}
}
希望对大家有所帮助。
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(","))
Swift5
(Java的子字符串方法):
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, Nick Michaels"
print(str.subString(from:7,to:20))
// print Nick Michaels
var str = "Hello, playground"
let indexcut = str.firstIndex(of: ",")
print(String(str[..<indexcut!]))
print(String(str[indexcut!...]))
你可以试着用这种方法,并会得到适当的结果。
如果你只是想获取一个特定字符的子字符串,你不需要先找到索引,你可以只使用prefix(while:)方法
let str = "Hello, playground"
let subString = str.prefix { $0 != "," } // "Hello" as a String.SubSequence
快速4 5 5+
Last的子字符串
let str = "Hello World"
let removeFirstSix = String(str.dropFirst(6))
print(removeFirstSix) //World
来自First的子字符串
let removeLastSix = String(str.dropLast(6))
print(removeLastSix) //Hello