我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
当前回答
在Swift 3中,没有对String类的扩展,就像我能做的那样简单!
let myString = "abcedfg"
let characterLocationIndex = myString.index(myString.startIndex, offsetBy: 3)
let myCharacter = myString[characterLocationIndex]
本例中的myCharacter为“3”。
其他回答
注意:请参阅Leo Dabus关于正确实现Swift 4和Swift 5的回答。
Swift 4或更高版本
Substring类型是在Swift 4中引入的,用于生成子字符串 通过与原始字符串共享存储,更快更有效,这就是下标函数应该返回的。
在这里试试吧
extension StringProtocol {
subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }
subscript(range: Range<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: ClosedRange<Int>) -> SubSequence {
let startIndex = index(self.startIndex, offsetBy: range.lowerBound)
return self[startIndex..<index(startIndex, offsetBy: range.count)]
}
subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] }
subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] }
subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] }
}
要将子字符串转换为字符串,您可以简单地 做字符串(字符串[0..2]),但你应该只做如果 您计划保留子字符串。否则,就更多了 有效地保持它为Substring。
It would be great if someone could figure out a good way to merge these two extensions into one. I tried extending StringProtocol without success, because the index method does not exist there. Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementation
为什么这不是内置的?
错误消息显示“请参阅文档注释以进行讨论”。Apple在文件unavailablestringapi .swift中提供了以下解释:
Subscripting strings with integers is not available. The concept of "the ith character in a string" has different interpretations in different libraries and system components. The correct interpretation should be selected according to the use case and the APIs involved, so String cannot be subscripted with an integer. Swift provides several different ways to access the character data stored inside strings. String.utf8 is a collection of UTF-8 code units in the string. Use this API when converting the string to UTF-8. Most POSIX APIs process strings in terms of UTF-8 code units. String.utf16 is a collection of UTF-16 code units in string. Most Cocoa and Cocoa touch APIs process strings in terms of UTF-16 code units. For example, instances of NSRange used with NSAttributedString and NSRegularExpression store substring offsets and lengths in terms of UTF-16 code units. String.unicodeScalars is a collection of Unicode scalars. Use this API when you are performing low-level manipulation of character data. String.characters is a collection of extended grapheme clusters, which are an approximation of user-perceived characters. Note that when processing strings that contain human-readable text, character-by-character processing should be avoided to the largest extent possible. Use high-level locale-sensitive Unicode algorithms instead, for example, String.localizedStandardCompare(), String.localizedLowercaseString, String.localizedStandardRangeOfString() etc.
斯威夫特4
String(Array(stringToIndex)[index])
这可能是一次性解决这个问题的最好方法。您可能希望首先将String转换为数组,然后再将结果转换为String。否则,将返回字符而不是字符串。
示例String(Array("HelloThere")[1])将返回"e"作为字符串。
(数组("HelloThere")[1]将返回"e"作为字符。
Swift不允许字符串像数组一样被索引,但这就完成了工作,用蛮力的方式。
斯威夫特5.1
这可能是所有答案中最简单的一个。
添加这个扩展:
extension String {
func retrieveFirstCharacter() -> String? {
guard self.count > 0 else { return nil }
let numberOfCharacters = self.count
return String(self.dropLast(numberOfCharacters - 1))
}
}
Swift 3:另一个解决方案(在操场测试)
extension String {
func substr(_ start:Int, length:Int=0) -> String? {
guard start > -1 else {
return nil
}
let count = self.characters.count - 1
guard start <= count else {
return nil
}
let startOffset = max(0, start)
let endOffset = length > 0 ? min(count, startOffset + length - 1) : count
return self[self.index(self.startIndex, offsetBy: startOffset)...self.index(self.startIndex, offsetBy: endOffset)]
}
}
用法:
let txt = "12345"
txt.substr(-1) //nil
txt.substr(0) //"12345"
txt.substr(0, length: 0) //"12345"
txt.substr(1) //"2345"
txt.substr(2) //"345"
txt.substr(3) //"45"
txt.substr(4) //"5"
txt.substr(6) //nil
txt.substr(0, length: 1) //"1"
txt.substr(1, length: 1) //"2"
txt.substr(2, length: 1) //"3"
txt.substr(3, length: 1) //"4"
txt.substr(3, length: 2) //"45"
txt.substr(3, length: 3) //"45"
txt.substr(4, length: 1) //"5"
txt.substr(4, length: 2) //"5"
txt.substr(5, length: 1) //nil
txt.substr(5, length: -1) //nil
txt.substr(-1, length: -1) //nil
看第一个字母:
first(str) // retrieve first letter
更多: http://sketchytech.blogspot.com/2014/08/swift-pure-swift-method-for-returning.html