我还没有弄清楚如何在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))

想法吗?


当前回答

一旦找到正确的语法,它比这里的任何答案都要简单得多。

我想把[和]

let myString = "[ABCDEFGHI]"
let startIndex = advance(myString.startIndex, 1) //advance as much as you like
let endIndex = advance(myString.endIndex, -1)
let range = startIndex..<endIndex
let myNewString = myString.substringWithRange( range )

结果是"ABCDEFGHI" startIndex和endIndex也可以用在

let mySubString = myString.substringFromIndex(startIndex)

等等!

PS:正如注释中所指出的,在xcode 7和iOS9附带的swift 2中有一些语法变化!

请看这一页

其他回答

您可以使用这些扩展来改进substringWithRange

斯威夫特2.3

extension String
{   
    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(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 str = "Hello, playground"

let substring1 = str.substringWithRange(0, end: 5) //Hello
let substring2 = str.substringWithRange(7, location: 10) //playground

你可以在我写的Swift String扩展https://bit.ly/JString中使用任何子字符串方法。

var string = "hello"
var sub = string.substringFrom(3) // or string[3...5]
println(sub)// "lo"

为Xcode 7更新。添加字符串扩展名:

Use:

var chuck: String = "Hello Chuck Norris"
chuck[6...11] // => Chuck

实现:

extension String {

    /**
     Subscript to allow for quick String substrings ["Hello"][0...1] = "He"
     */
    subscript (r: Range<Int>) -> String {
        get {
            let start = self.startIndex.advancedBy(r.startIndex)
            let end = self.startIndex.advancedBy(r.endIndex - 1)
            return self.substringWithRange(start..<end)
        }
    }

}

一旦找到正确的语法,它比这里的任何答案都要简单得多。

我想把[和]

let myString = "[ABCDEFGHI]"
let startIndex = advance(myString.startIndex, 1) //advance as much as you like
let endIndex = advance(myString.endIndex, -1)
let range = startIndex..<endIndex
let myNewString = myString.substringWithRange( range )

结果是"ABCDEFGHI" startIndex和endIndex也可以用在

let mySubString = myString.substringFromIndex(startIndex)

等等!

PS:正如注释中所指出的,在xcode 7和iOS9附带的swift 2中有一些语法变化!

请看这一页

斯威夫特3.0

我决定有一个小乐趣与此,并产生一个扩展的字符串。我可能没有正确地使用截断这个词在我让函数实际做的事情中。

extension String {

    func truncate(from initialSpot: Int, withLengthOf endSpot: Int) -> String? {

        guard endSpot > initialSpot else { return nil }
        guard endSpot + initialSpot <= self.characters.count else { return nil }

        let truncated = String(self.characters.dropFirst(initialSpot))
        let lastIndex = truncated.index(truncated.startIndex, offsetBy: endSpot)

        return truncated.substring(to: lastIndex)
    }

}

let favGameOfThronesSong = "Light of the Seven"

let word = favGameOfThronesSong.truncate(from: 1, withLengthOf: 4)
// "ight"