我有以下用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中使用部分范围的切片下标?
我有以下用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中使用部分范围的切片下标?
Answers:
您应将一侧留空,因此命名为“部分范围”。
let newStr = str[..<index]
运算符的部分范围相同,只是将另一侧留空:
let newStr = str[index...]
请记住,这些范围运算符返回Substring
。如果要将其转换为字符串,请使用String
的初始化函数:
let newStr = String(str[..<index])
您可以在此处阅读有关新子字符串的更多信息。
str[..<index]
返回Substring
。如果你想newStr
成为一个,String
你必须写:let newStr = "\(str[..<index])"
Substring
可能会造成一些混乱,因为您真正想要实现的是String
初始化:let newStr = String(str[..<index])
。
Cannot subscript a value of type 'String' with an index of type 'PartialRangeUpTo<Int>'
。在那里必须使用什么类型的值?
str[..<str.index(str.startIndex, offsetBy: 8)]
或类似的东西。请记住,这str.index
是函数的线性时间运算offsetBy
。
str.prefix(8)
将子字符串(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
let text = "Hello world"
text[0] // H
text[...3] // "Hell"
text[6..<text.count] // world
text[NSRange(location: 6, length: 3)] // wor
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)
}
}
您的代码到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 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
from
到to-1
,例如"Hello".substring(1,4)
返回“ ell”)。进行少量修改(startIndex..<endIndex
),这是到目前为止我发现的最好的解决方案,只需几行代码即可实现。
一些有用的扩展:
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)
}
}
uppercasedFirstCharacter
Swift3和Swift4 中便利属性的示例。
属性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"
您可以使用对类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)
}
}
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 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: "+")
结果示例:“ 1511508780012”
PS:可选件必须拆开。请在必要时添加类型安全检查。
编程时,我经常会有只带有纯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)
}
}
使用此方法可以获得特定范围的字符串。您需要传递起始索引,然后传递所需的字符总数。
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])
}
}
这是我的解决方案,没有警告,没有错误,但是很完美
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)])
希望这会有所帮助:-
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)
希望对您有所帮助。
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(","))