你如何使用 String.substringWithRange?(或者,范围如何在 Swift 中工作?) [英] How do you use String.substringWithRange? (or, how do Ranges work in Swift?)
问题描述
我还没有弄清楚如何在 Swift 中获取 String
的子字符串:
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)
我无法在 Swift 中创建范围.Playground 中的自动完成功能并不是很有帮助 - 这就是它的建议:
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>)
我在 Swift 标准参考库中没有找到任何有用的内容.这是另一个疯狂的猜测:
I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess:
return str.substringWithRange(Range(0, 1))
还有这个:
let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)
return str.substringWithRange(r)
我看过其他答案(在 Swift 字符串中查找字符索引) 似乎表明由于 String
是 NSString
的桥接类型,旧"方法应该可以工作,但不清楚如何 - 例如,这不会也不起作用(似乎不是有效的语法):
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))
想法?
推荐答案
您可以使用 substringWithRange 方法.它需要一个开始和结束的 String.Index.
You can use the substringWithRange method. It takes a start and end String.Index.
var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground"
要更改开始和结束索引,请使用 advancedBy(n).
To change the start and end index, use advancedBy(n).
var str = "Hello, playground"
str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun"
你仍然可以在 NSRange 中使用 NSString 方法,但你必须确保你使用的是这样的 NSString:
You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this:
let myNSString = str as NSString
myNSString.substringWithRange(NSRange(location: 0, length: 3))
注意:正如 JanX2 提到的,第二种方法对于 unicode 字符串是不安全的.
Note: as JanX2 mentioned, this second method is not safe with unicode strings.
这篇关于你如何使用 String.substringWithRange?(或者,范围如何在 Swift 中工作?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!