我想学习最好/最简单的方法,将一个字符串转换为另一个字符串,但只有一个子集,从一个字符的开始到最后一个索引。
例如,将“ www.stackoverflow.com”转换为“ www.stackoverflow”。什么样的代码片段会做到这一点,并且最快捷?(我希望这不会引起争论,但是我找不到关于如何在Swift中处理子字符串的好课程。
我想学习最好/最简单的方法,将一个字符串转换为另一个字符串,但只有一个子集,从一个字符的开始到最后一个索引。
例如,将“ www.stackoverflow.com”转换为“ www.stackoverflow”。什么样的代码片段会做到这一点,并且最快捷?(我希望这不会引起争论,但是我找不到关于如何在Swift中处理子字符串的好课程。
Answers:
最好的方法是substringToIndex
结合使用endIndex
属性和advance
全局功能。
var string1 = "www.stackoverflow.com"
var index1 = advance(string1.endIndex, -4)
var substring1 = string1.substringToIndex(index1)
使用rangeOfString
并设置options
为.BackwardsSearch
var string2 = "www.stackoverflow.com"
var index2 = string2.rangeOfString(".", options: .BackwardsSearch)?.startIndex
var substring2 = string2.substringToIndex(index2!)
没有扩展,纯真的Swift
advance
现在是的一部分,Index
称为advancedBy
。您这样做:
var string1 = "www.stackoverflow.com"
var index1 = string1.endIndex.advancedBy(-4)
var substring1 = string1.substringToIndex(index1)
您无法调用advancedBy
a,String
因为它具有可变大小的元素。您必须使用index(_, offsetBy:)
。
var string1 = "www.stackoverflow.com"
var index1 = string1.index(string1.endIndex, offsetBy: -4)
var substring1 = string1.substring(to: index1)
许多事情已经重命名。这些案件都写在驼峰,startIndex
成了lowerBound
。
var string2 = "www.stackoverflow.com"
var index2 = string2.range(of: ".", options: .backwards)?.lowerBound
var substring2 = string2.substring(to: index2!)
另外,我不建议强制展开index2
。您可以使用可选的绑定或map
。就个人而言,我更喜欢使用map
:
var substring3 = index2.map(string2.substring(to:))
Swift 3版本仍然有效,但是现在您可以使用带有索引范围的下标:
let string1 = "www.stackoverflow.com"
let index1 = string1.index(string1.endIndex, offsetBy: -4)
let substring1 = string1[..<index1]
第二种方法保持不变:
let string2 = "www.stackoverflow.com"
let index2 = string2.range(of: ".", options: .backwards)?.lowerBound
let substring3 = index2.map(string2.substring(to:))
string1.endIndex.advancedBy(-4)
为我工作,而不是advance
NSString
显然也很糟糕,因为最终我们所有人都希望摆脱Foundation(旧版)类。所以。。。
string1[..<index1]
。不需要string1.startIndex
。
func lastIndexOfCharacter(_ c: Character) -> Int? {
return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}
自从advancedBy(Int)
Swift 3使用String
的方法消失了index(String.Index, Int)
。String
使用子字符串和朋友查看此扩展名:
public extension String {
//right is the first encountered string after left
func between(_ left: String, _ right: String) -> String? {
guard let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
, leftRange.upperBound <= rightRange.lowerBound
else { return nil }
let sub = self.substring(from: leftRange.upperBound)
let closestToLeftRange = sub.range(of: right)!
return sub.substring(to: closestToLeftRange.lowerBound)
}
var length: Int {
get {
return self.characters.count
}
}
func substring(to : Int) -> String {
let toIndex = self.index(self.startIndex, offsetBy: to)
return self.substring(to: toIndex)
}
func substring(from : Int) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: from)
return self.substring(from: fromIndex)
}
func substring(_ r: Range<Int>) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
return self.substring(with: Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex)))
}
func character(_ at: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: at)]
}
func lastIndexOfCharacter(_ c: Character) -> Int? {
guard let index = range(of: String(c), options: .backwards)?.lowerBound else
{ return nil }
return distance(from: startIndex, to: index)
}
}
public extension String {
//right is the first encountered string after left
func between(_ left: String, _ right: String) -> String? {
guard
let leftRange = range(of: left), let rightRange = range(of: right, options: .backwards)
, leftRange.upperBound <= rightRange.lowerBound
else { return nil }
let sub = self[leftRange.upperBound...]
let closestToLeftRange = sub.range(of: right)!
return String(sub[..<closestToLeftRange.lowerBound])
}
var length: Int {
get {
return self.count
}
}
func substring(to : Int) -> String {
let toIndex = self.index(self.startIndex, offsetBy: to)
return String(self[...toIndex])
}
func substring(from : Int) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: from)
return String(self[fromIndex...])
}
func substring(_ r: Range<Int>) -> String {
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
return String(self[indexRange])
}
func character(_ at: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: at)]
}
func lastIndexOfCharacter(_ c: Character) -> Int? {
guard let index = range(of: String(c), options: .backwards)?.lowerBound else
{ return nil }
return distance(from: startIndex, to: index)
}
}
用法:
let text = "www.stackoverflow.com"
let at = text.character(3) // .
let range = text.substring(0..<3) // www
let from = text.substring(from: 4) // stackoverflow.com
let to = text.substring(to: 16) // www.stackoverflow
let between = text.between(".", ".") // stackoverflow
let substringToLastIndexOfChar = text.lastIndexOfCharacter(".") // 17
PS开发人员被迫处理String.Index
而不是简单处理,这确实很奇怪Int
。为什么我们要为内部String
机制而烦恼而不仅仅是简单的substring()
方法?
encodedOffset
检查此评论和正确的方式来实现这一目标stackoverflow.com/questions/34540185/...
我可以使用下标(s[start..<end]
)来实现:
let s = "www.stackoverflow.com"
let start = s.startIndex
let end = s.index(s.endIndex, offsetBy: -4)
let substring = s[start..<end] // www.stackoverflow
编辑/更新:
在Swift 4或更高版本(Xcode 10.0+)中,您可以使用新的BidirectionalCollection 方法lastIndex(of :)
func lastIndex(of element: Element) -> Int?
let string = "www.stackoverflow.com"
if let lastIndex = string.lastIndex(of: ".") {
let subString = string[..<lastIndex] // "www.stackoverflow"
}
这是我的方法。您可以用相同的方式进行操作,也可以使用此代码来获得想法。
let s = "www.stackoverflow.com"
s.substringWithRange(0..<s.lastIndexOf("."))
这是我使用的扩展名:
import Foundation
extension String {
var length: Int {
get {
return countElements(self)
}
}
func indexOf(target: String) -> Int {
var range = self.rangeOfString(target)
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int {
var startRange = advance(self.startIndex, startIndex)
var range = self.rangeOfString(target, options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: startRange, end: self.endIndex))
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func lastIndexOf(target: String) -> Int {
var index = -1
var stepIndex = self.indexOf(target)
while stepIndex > -1 {
index = stepIndex
if stepIndex + target.length < self.length {
stepIndex = indexOf(target, startIndex: stepIndex + target.length)
} else {
stepIndex = -1
}
}
return index
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
}
通常,我是扩展的强烈支持者,尤其是对于诸如字符串操作,搜索和切片之类的需求。
String
具有内置的子字符串功能:
extension String : Sliceable {
subscript (subRange: Range<String.Index>) -> String { get }
}
如果您想要的是“转到字符的第一个索引”,则可以使用内置find()
函数获取子字符串:
var str = "www.stackexchange.com"
str[str.startIndex ..< find(str, ".")!] // -> "www"
要找到最后一个索引,我们可以实现findLast()
。
/// Returns the last index where `value` appears in `domain` or `nil` if
/// `value` is not found.
///
/// Complexity: O(\ `countElements(domain)`\ )
func findLast<C: CollectionType where C.Generator.Element: Equatable>(domain: C, value: C.Generator.Element) -> C.Index? {
var last:C.Index? = nil
for i in domain.startIndex..<domain.endIndex {
if domain[i] == value {
last = i
}
}
return last
}
let str = "www.stackexchange.com"
let substring = map(findLast(str, ".")) { str[str.startIndex ..< $0] } // as String?
// if "." is found, substring has some, otherwise `nil`
添加:
也许,BidirectionalIndexType
专业版的findLast
速度更快:
func findLast<C: CollectionType where C.Generator.Element: Equatable, C.Index: BidirectionalIndexType>(domain: C, value: C.Generator.Element) -> C.Index? {
for i in lazy(domain.startIndex ..< domain.endIndex).reverse() {
if domain[i] == value {
return i
}
}
return nil
}
您可以使用以下扩展名:
斯威夫特2.3
extension String
{
func substringFromIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringFromIndex(self.startIndex.advancedBy(index))
}
func substringToIndex(index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substringToIndex(self.startIndex.advancedBy(index))
}
func substringWithRange(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(end))
return self.substringWithRange(range)
}
func substringWithRange(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let range = Range(start: self.startIndex.advancedBy(start), end: self.startIndex.advancedBy(start + location))
return self.substringWithRange(range)
}
}
迅捷3
extension String
{
func substring(from index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substring(from: self.characters.index(self.startIndex, offsetBy: index))
}
func substring(to index: Int) -> String
{
if (index < 0 || index > self.characters.count)
{
print("index \(index) out of bounds")
return ""
}
return self.substring(to: self.characters.index(self.startIndex, offsetBy: index))
}
func substring(start: Int, end: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if end < 0 || end > self.characters.count
{
print("end index \(end) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: end)
let range = startIndex..<endIndex
return self.substring(with: range)
}
func substring(start: Int, location: Int) -> String
{
if (start < 0 || start > self.characters.count)
{
print("start index \(start) out of bounds")
return ""
}
else if location < 0 || start + location > self.characters.count
{
print("end index \(start + location) out of bounds")
return ""
}
let startIndex = self.characters.index(self.startIndex, offsetBy: start)
let endIndex = self.characters.index(self.startIndex, offsetBy: start + location)
let range = startIndex..<endIndex
return self.substring(with: range)
}
}
用法:
let string = "www.stackoverflow.com"
let substring = string.substringToIndex(string.characters.count-4)
斯威夫特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..<rightIndex)
}
/// Get substring, e.g. -> "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..<rightIndex)
}
}
}
您可以如下进行测试:
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"))
检查https://gitlab.com/seriyvolk83/SwiftEx库。它包含这些和其他有用的方法。
您是否要从字符串的一个字符的起始索引到最后一个索引获取字符串的子字符串?如果是这样,则可以选择以下Swift 2.0+方法之一。
Foundation
获取包含字符的最后一个索引的子字符串:
import Foundation
let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
print(string.substringToIndex(rangeOfIndex.endIndex))
}
// prints "www.stackoverflow."
获取不包含字符的最后一个索引的子字符串:
import Foundation
let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
print(string.substringToIndex(rangeOfIndex.startIndex))
}
// prints "www.stackoverflow"
如果您需要重复这些操作,扩展String
可以是一个很好的解决方案:
import Foundation
extension String {
func substringWithLastInstanceOf(character: Character) -> String? {
if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
return self.substringToIndex(rangeOfIndex.endIndex)
}
return nil
}
func substringWithoutLastInstanceOf(character: Character) -> String? {
if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
return self.substringToIndex(rangeOfIndex.startIndex)
}
return nil
}
}
print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))
/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/
Foundation
获取包含字符的最后一个索引的子字符串:
let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
print(string[string.startIndex ..< reverseIndex.base])
}
// prints "www.stackoverflow."
获取不包含字符的最后一个索引的子字符串:
let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
print(string[string.startIndex ..< reverseIndex.base.advancedBy(-1)])
}
// prints "www.stackoverflow"
如果您需要重复这些操作,扩展String
可以是一个很好的解决方案:
extension String {
func substringWithLastInstanceOf(character: Character) -> String? {
if let reverseIndex = characters.reverse().indexOf(".") {
return self[self.startIndex ..< reverseIndex.base]
}
return nil
}
func substringWithoutLastInstanceOf(character: Character) -> String? {
if let reverseIndex = characters.reverse().indexOf(".") {
return self[self.startIndex ..< reverseIndex.base.advancedBy(-1)]
}
return nil
}
}
print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))
/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/
如果您知道索引,这是获取子字符串的简便方法:
let s = "www.stackoverflow.com"
let result = String(s.characters.prefix(17)) // "www.stackoverflow"
如果您的索引超过字符串的长度,它不会使应用程序崩溃:
let s = "short"
let result = String(s.characters.prefix(17)) // "short"
这两个示例都已准备好Swift 3。
增加cl嗒声的一件事是重复stringVar
:
stringVar [ stringVar .index(stringVar .startIndex,offsetBy:...)
在Swift 4中
扩展可以减少其中的一些:
extension String {
func index(at: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: at)
}
}
然后,用法:
let string = "abcde"
let to = string[..<string.index(at: 3)] // abc
let from = string[string.index(at: 3)...] // de
应该注意的是to
和from
是类型Substring
(或String.SubSequance
)。它们不分配新的字符串,并且处理效率更高。
要获取String
类型,Substring
需要将其强制转换为String
:
let backToString = String(from)
这是最后分配字符串的地方。
func substr(myString: String, start: Int, clen: Int)->String
{
var index2 = string1.startIndex.advancedBy(start)
var substring2 = string1.substringFromIndex(index2)
var index1 = substring2.startIndex.advancedBy(clen)
var substring1 = substring2.substringToIndex(index1)
return substring1
}
substr(string1, start: 3, clen: 5)
迅捷3
let string = "www.stackoverflow.com"
let first3Characters = String(string.characters.prefix(3)) // www
let lastCharacters = string.characters.dropFirst(4) // stackoverflow.com (it would be a collection)
//or by index
let indexOfFouthCharacter = olNumber.index(olNumber.startIndex, offsetBy: 4)
let first3Characters = olNumber.substring(to: indexOfFouthCharacter) // www
let lastCharacters = olNumber.substring(from: indexOfFouthCharacter) // .stackoverflow.com
很好的理解文章,为什么我们需要这个
我用两个子字符串方法扩展了String。您可以像这样从/到范围或从/长度调用子字符串:
var bcd = "abcdef".substring(1,to:3)
var cde = "abcdef".substring(2,to:-2)
var cde = "abcdef".substring(2,length:3)
extension String {
public func substring(from:Int = 0, var to:Int = -1) -> String {
if to < 0 {
to = self.length + to
}
return self.substringWithRange(Range<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(to+1)))
}
public func substring(from:Int = 0, length:Int) -> String {
return self.substringWithRange(Range<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(from+length)))
}
}
Swift 2.0 下面的代码在XCode 7.2上进行了测试。请参考底部的屏幕截图
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var mainText = "http://stackoverflow.com"
var range = Range(start: mainText.startIndex.advancedBy(7), end: mainText.startIndex.advancedBy(24))
var subText = mainText.substringWithRange(range)
//OR Else use below for LAST INDEX
range = Range(start: mainText.startIndex.advancedBy(7), end: mainText.endIndex)
subText = mainText.substringWithRange(range)
}
}
在Swift 5中
我们需要String.Index
代替简单的Int值来表示Index。
还要记住,当我们尝试从Swift String
(值类型)获取subString时,实际上我们必须使用Sequence
协议进行迭代,该协议返回String.SubSequence
type而不是String
type。
要返回String
从String.SubSequence
,使用String(subString)
示例如下:
let string = "https://stackoverflow.com"
let firstIndex = String.Index(utf16Offset: 0, in: string)
let lastIndex = String.Index(utf16Offset: 6, in: string)
let subString = String(string[firstIndex...lastIndex])
对于Swift 2.0,它是这样的:
var string1 = "www.stackoverflow.com"
var index1 = string1.endIndex.advancedBy(-4)
var substring1 = string1.substringToIndex(index1)
我已经修改了andrewz的帖子,使其与Swift 2.0(也许还有Swift 3.0)兼容。以我的拙见,此扩展更易于理解,并且与其他语言(如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<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(nto+1)))
}
func substring(from:Int = 0, length:Int) -> String {
return self.substringWithRange(Range<String.Index>(
start:self.startIndex.advancedBy(from),
end:self.startIndex.advancedBy(from+length)))
}
}
我还为Swift 4构建了一个简单的String-extension:
extension String {
func subStr(s: Int, l: Int) -> String { //s=start, l=lenth
let r = Range(NSRange(location: s, length: l))!
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
let indexRange = Range<String.Index>(uncheckedBounds: (lower: fromIndex, upper: toIndex))
return String(self[indexRange])
}
}
因此,您可以像这样轻松地调用它:
"Hallo world".subStr(s: 1, l: 3) //prints --> "all"
尝试以下Int-based
解决方法:
extension String {
// start and end is included
func intBasedSubstring(_ start: Int, _ end: Int) -> String {
let endOffset: Int = -(count - end - 1)
let startIdx = self.index(startIndex, offsetBy: start)
let endIdx = self.index(endIndex, offsetBy: endOffset)
return String(self[startIdx..<endIdx])
}
}
注意:这只是一种做法。它不检查边界。进行修改以满足您的需求。
这是在Swift中获取子字符串的简单方法
import UIKit
var str = "Hello, playground"
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))