我还没有弄清楚如何在Swift中获得字符串的子字符串:

var str = “Hello, playground”
func test(str: String) -> String {
 return str.substringWithRange( /* What goes here? */ )
}
test (str)

我不能在Swift中创建一个范围。自动完成在游乐场不是超级有用的-这是它的建议:

return str.substringWithRange(aRange: Range<String.Index>)

我在Swift标准参考库中没有找到任何有用的东西。下面是另一个大胆的猜测:

return str.substringWithRange(Range(0, 1))

这:

let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)
return str.substringWithRange(r)

我看到了其他答案(在Swift字符串中查找字符索引),似乎表明,由于字符串是NSString的桥类型,“旧”方法应该工作,但不清楚如何-例如,这也不工作(似乎不是有效的语法):

let x = str.substringWithRange(NSMakeRange(0, 3))

想法吗?


当前回答

在我写这篇文章的时候,没有一个扩展是完全兼容Swift 4.2的,所以这里有一个涵盖了我能想到的所有需求:

extension String {
    func substring(from: Int?, to: Int?) -> String {
        if let start = from {
            guard start < self.count else {
                return ""
            }
        }

        if let end = to {
            guard end >= 0 else {
                return ""
            }
        }

        if let start = from, let end = to {
            guard end - start >= 0 else {
                return ""
            }
        }

        let startIndex: String.Index
        if let start = from, start >= 0 {
            startIndex = self.index(self.startIndex, offsetBy: start)
        } else {
            startIndex = self.startIndex
        }

        let endIndex: String.Index
        if let end = to, end >= 0, end < self.count {
            endIndex = self.index(self.startIndex, offsetBy: end + 1)
        } else {
            endIndex = self.endIndex
        }

        return String(self[startIndex ..< endIndex])
    }

    func substring(from: Int) -> String {
        return self.substring(from: from, to: nil)
    }

    func substring(to: Int) -> String {
        return self.substring(from: nil, to: to)
    }

    func substring(from: Int?, length: Int) -> String {
        guard length > 0 else {
            return ""
        }

        let end: Int
        if let start = from, start > 0 {
            end = start + length - 1
        } else {
            end = length - 1
        }

        return self.substring(from: from, to: end)
    }

    func substring(length: Int, to: Int?) -> String {
        guard let end = to, end > 0, length > 0 else {
            return ""
        }

        let start: Int
        if let end = to, end - length > 0 {
            start = end - length + 1
        } else {
            start = 0
        }

        return self.substring(from: start, to: to)
    }
}

然后,你可以使用:

let string = "Hello,World!"

字符串。substring(from: 1, to: 7)得到你:ello,Wo

字符串。substring(to: 7)得到你:Hello,Wo

字符串。substring(from: 3)得到你:lo,World!

字符串。子字符串(从:1,长度:4)得到你:ello

字符串。substring(长度:4,到:7)得到你:o,Wo

更新的子字符串(from: Int?, length: Int)支持从零开始。

其他回答

在Swift3

例如:变量“Duke James Thomas”,我们需要得到“James”。

let name = "Duke James Thomas"
let range: Range<String.Index> = name.range(of:"James")!
let lastrange: Range<String.Index> = img.range(of:"Thomas")!
var middlename = name[range.lowerBound..<lstrange.lowerBound]
print (middlename)

String的简单扩展:

extension String {

    func substringToIndex(index: Int) -> String {
        return self[startIndex...startIndex.advancedBy(min(index, characters.count - 1))]
    }
}

斯威夫特2

简单的

let str = "My String"
let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)]
//"Strin"

斯威夫特3

let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)

str[startIndex...endIndex]       // "Strin"
str.substring(to: startIndex)    // "My "
str.substring(from: startIndex)  // "String"

斯威夫特4

substring(to:)和substring(from:)在Swift 4中已弃用。

String(str[..<startIndex])    // "My "
String(str[startIndex...])    // "String"
String(str[startIndex...endIndex])    // "Strin"

借鉴Rob Napier的经验,我开发了这些常见的字符串扩展,其中两个是:

subscript (r: Range<Int>) -> String
{
    get {
        let startIndex = advance(self.startIndex, r.startIndex)
        let endIndex = advance(self.startIndex, r.endIndex - 1)

        return self[Range(start: startIndex, end: endIndex)]
    }
}

func subString(startIndex: Int, length: Int) -> String
{
    var start = advance(self.startIndex, startIndex)
    var end = advance(self.startIndex, startIndex + length)
    return self.substringWithRange(Range<String.Index>(start: start, end: end))
}

用法:

"Awesome"[3...7] //"some"
"Awesome".subString(3, length: 4) //"some"

首先创建范围,然后是子字符串。你可以使用fromIndex..<toIndex语法如下:

let range = fullString.startIndex..<fullString.startIndex.advancedBy(15) // 15 first characters of the string
let substring = fullString.substringWithRange(range)