How do you use String.substringWithRange? (or, how

2019-01-01 06:00发布

I have not yet been able to figure out how to get a substring of a String in Swift:

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

I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is what it suggests:

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

I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:

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

And this:

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

I've seen other answers (Finding index of character in Swift String) that seem to suggest that since String is a bridge type for NSString, the "old" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax):

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

Thoughts?

标签: swift
30条回答
君临天下
2楼-- · 2019-01-01 07:01

First create the range, then the substring. You can use fromIndex..<toIndex syntax like so:

let range = fullString.startIndex..<fullString.startIndex.advancedBy(15) // 15 first characters of the string
let substring = fullString.substringWithRange(range)
查看更多
琉璃瓶的回忆
3楼-- · 2019-01-01 07:01

http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/ shows that this works well:

var str = "abcd"
str = str.substringToIndex(1)
查看更多
十年一品温如言
4楼-- · 2019-01-01 07:02

Updated for Xcode 7. Adds String extension:

Use:

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

Implementation:

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)
        }
    }

}
查看更多
爱死公子算了
5楼-- · 2019-01-01 07:04

At the time I'm writing, no extension is perfectly Swift 3 compatible, so here is one that covers all the needs I could think of:

extension String {
func substring(from: Int?, to: Int?) -> String {
    if let start = from {
        guard start < self.characters.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.characters.count {
        endIndex = self.index(self.startIndex, offsetBy: end + 1)
    } else {
        endIndex = self.endIndex
    }

    return 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)
}
}

And then, you can use:

let string = "Hello,World!"

string.substring(from: 1, to: 7)gets you: ello,Wo

string.substring(to: 7)gets you: Hello,Wo

string.substring(from: 3)gets you: lo,World!

string.substring(from: 1, length: 4)gets you: ello

string.substring(length: 4, to: 7)gets you: o,Wo

Updated substring(from: Int?, length: Int) to support starting from zero.

查看更多
人间绝色
6楼-- · 2019-01-01 07:04

Well, I had the same issue and solved with the "bridgeToObjectiveC()" function:

var helloworld = "Hello World!"
var world = helloworld.bridgeToObjectiveC().substringWithRange(NSMakeRange(6,6))
println("\(world)") // should print World!

Please note that in the example, substringWithRange in conjunction with NSMakeRange take the part of the string starting at index 6 (character "W") and finishing at index 6 + 6 positions ahead (character "!")

Cheers.

查看更多
公子世无双
7楼-- · 2019-01-01 07:06

In new Xcode 7.0 use

//: Playground - noun: a place where people can play

import UIKit

var name = "How do you use String.substringWithRange?"
let range = name.startIndex.advancedBy(0)..<name.startIndex.advancedBy(10)
name.substringWithRange(range)

//OUT:

enter image description here

查看更多
登录 后发表回答