我想学习将字符串转换为另一个字符串的最佳/最简单方法,但只有一个子集,从头开始并转到字符的最后一个索引。
例如,转换" www.stackoverflow.com"到" www.stackoverflow"。什么代码片段可以做到这一点,并且是最快速的? (我希望这不会带来争论,但我无法在如何处理Swift中的子串中找到很好的教训。
答案 0 :(得分:192)
最好的方法是将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
上呼叫String
,因为它具有可变大小的元素。您必须使用index(_, offsetBy:)
。
var string1 = "www.stackoverflow.com"
var index1 = string1.index(string1.endIndex, offsetBy: -4)
var substring1 = string1.substring(to: index1)
很多东西都被重命名了。这些案例是用camelCase编写的,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:))
答案 1 :(得分:21)
func lastIndexOfCharacter(_ c: Character) -> Int? {
return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}
由于Swift 3使用advancedBy(Int)
的方法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? {
return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}
}
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? {
return range(of: String(c), options: .backwards)?.lowerBound.encodedOffset
}
}
<强>用法:强>
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
P.S。开发人员被迫处理String.Index
而不是普通Int
,这真的很奇怪。我们为什么要为内部String
机制而烦恼,而不只是简单的substring()
方法?
答案 2 :(得分:12)
我会使用下标(s[start..<end]
):
let s = "www.stackoverflow.com"
let start = s.startIndex
let end = s.endIndex.advancedBy(-4)
let substring = s[start..<end] // www.stackoverflow
let s = "www.stackoverflow.com"
let start = s.startIndex
let end = s.index(s.endIndex, offsetBy: -4)
let substring = s[start..<end] // www.stackoverflow
答案 3 :(得分:8)
例如,将“www.stackoverflow.com”转换为“www.stackoverflow”。什么代码片段可以做到这一点,并且是最快速的?
它可以更像Swift吗?
let string = "www.stackoverflow.com".stringByDeletingPathExtension // "www.stackoverflow"
更新: Xcode 7.2.1•Swift 2.1.1
extension String {
var nsValue: NSString {
return self
}
}
let string = "www.stackoverflow.com".nsValue.stringByDeletingPathExtension // "www.stackoverflow"
编辑/更新:
在 Swift 4或更高版本(Xcode 10.0+)中,您可以使用新数组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"
}
答案 4 :(得分:7)
以下是我的表现方式。你可以用同样的方式做到这一点,或者用这个代码来表达想法。
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)
}
}
信用albertbori / Common Swift String Extensions
一般来说,我是扩展的强力支持者,特别是对于字符串操作,搜索和切片等需求。
答案 5 :(得分:4)
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
}
答案 6 :(得分:4)
您可以使用以下扩展程序:
Swift 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)
}
}
Swift 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)
答案 7 :(得分:3)
您是否希望从起始索引到其中一个字符的最后一个索引获取字符串的子字符串?如果是这样,您可以选择以下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")
*/
答案 8 :(得分:3)
斯威夫特3:
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"))
答案 9 :(得分:3)
如果您知道索引,这是获取子字符串的简单方法:
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 ready 。
答案 10 :(得分:2)
添加咔嗒声的一件事是重复DocumentRoot "/home/xfce/Documents/www/"
<Directory "/home/xfce/Documents/www/">
:
stringVar [ stringVar .index( stringVar .startIndex,offsetBy:...)
在 Swift 4
中扩展可以减少其中一些:
stringVar
然后,用法:
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
这是最终分配字符串的地方。
答案 11 :(得分:2)
Swift 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
好article用于理解,为什么我们需要这个
答案 12 :(得分:2)
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)
答案 13 :(得分:1)
在Swift 5中
我们需要String.Index
而不是简单的Int值来表示Index。
还请记住,当我们尝试从Swift String
(值类型)获取subString时,实际上我们必须使用Sequence
协议进行迭代,该协议返回String.SubSequence
类型而不是{{1 }}类型。
要从String
返回String
,请使用String.SubSequence
示例如下:
String(subString)
答案 14 :(得分:1)
我使用两个子字符串方法扩展了String。您可以使用from / to范围或from / length调用substring:
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)))
}
}
答案 15 :(得分:0)
var url = "www.stackoverflow.com"
let str = path.suffix(3)
print(str) //low
答案 16 :(得分:0)
尝试此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])
}
}
注意:这只是一种做法。它不检查边界。进行修改以满足您的需求。
答案 17 :(得分:0)
var myString = "abcde"
var subString = myString[2,4] // The result will be "cde"
extension String {
subscript(startIndex: Int, endIndex: Int) -> String {
let start = self.index(self.startIndex, offsetBy: startIndex)
let end = self.index(self.startIndex, offsetBy: endIndex)
let range = start...end
return String(self[range])
}
}
答案 18 :(得分:0)
我还为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"
答案 19 :(得分:0)
我修改了andrewz&#39;发布使其与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)))
}
}
答案 20 :(得分:0)
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)
}
}
答案 21 :(得分:0)
对于 Swift 2.0 ,就像这样:
var string1 = "www.stackoverflow.com"
var index1 = string1.endIndex.advancedBy(-4)
var substring1 = string1.substringToIndex(index1)
答案 22 :(得分:-1)
这是在Swift
中获取子字符串的简单方法import UIKit
var str = "Hello, playground"
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))