我怎样才能得到字符串的第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,请参阅文档注释讨论
当前回答
斯威夫特5.3
我觉得这很优雅。“Hacking with Swift”的Paul Hudson提出了以下解决方案:
@available (macOS 10.15, * )
extension String {
subscript(idx: Int) -> String {
String(self[index(startIndex, offsetBy: idx)])
}
}
然后,要从字符串中获取一个字符,你只需做:
var string = "Hello, world!"
var firstChar = string[0] // No error, returns "H" as a String
注意:我只是想补充,这将返回一个字符串指出在评论。我认为这对Swift用户来说可能是意想不到的,但我经常需要一个字符串来直接在我的代码中使用,而不是字符类型,所以它确实简化了我的代码,避免了后来从字符到字符串的转换。
其他回答
斯威夫特3
extension String {
public func charAt(_ i: Int) -> Character {
return self[self.characters.index(self.startIndex, offsetBy: i)]
}
public subscript (i: Int) -> String {
return String(self.charAt(i) as Character)
}
public subscript (r: Range<Int>) -> String {
return substring(with: self.characters.index(self.startIndex, offsetBy: r.lowerBound)..<self.characters.index(self.startIndex, offsetBy: r.upperBound))
}
public subscript (r: CountableClosedRange<Int>) -> String {
return substring(with: self.characters.index(self.startIndex, offsetBy: r.lowerBound)..<self.characters.index(self.startIndex, offsetBy: r.upperBound))
}
}
使用
let str = "Hello World"
let sub = str[0...4]
有用的编程技巧和技巧(我写的)
Swift3
可以使用下标语法访问特定String索引处的Character。
let greeting = "Guten Tag!"
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index] // a
访问https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
或者我们可以在Swift 4中做一个字符串扩展
extension String {
func getCharAtIndex(_ index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
用法:
let foo = "ABC123"
foo.getCharAtIndex(2) //C
我也有同样的问题。简单地这样做:
var aString: String = "test"
var aChar:unichar = (aString as NSString).characterAtIndex(0)
在Swift 5中,不扩展字符串:
var str = "ABCDEFGH"
for char in str {
if(char == "C") { }
}
以上Swift代码与Java代码相同:
int n = 8;
var str = "ABCDEFGH"
for (int i=0; i<n; i++) {
if (str.charAt(i) == 'C') { }
}
斯威夫特3:
extension String {
func substring(fromPosition: UInt, toPosition: UInt) -> String? {
guard fromPosition <= toPosition else {
return nil
}
guard toPosition < UInt(characters.count) else {
return nil
}
let start = index(startIndex, offsetBy: String.IndexDistance(fromPosition))
let end = index(startIndex, offsetBy: String.IndexDistance(toPosition) + 1)
let range = start..<end
return substring(with: range)
}
}
"ffaabbcc".substring(fromPosition: 2, toPosition: 5) // return "aabb"