Get nth character of a string in Swift programming language

后端 未结 30 2798
一整个雨季
一整个雨季 2020-11-22 01:26

How can I get the nth character of a string? I tried bracket([]) accessor with no luck.

var string = \"Hello, world!\"

var firstChar = string[         


        
30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 01:37

    Swift3

    You can use subscript syntax to access the Character at a particular String index.

    let greeting = "Guten Tag!"
    let index = greeting.index(greeting.startIndex, offsetBy: 7)
    greeting[index] // a
    

    Visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

    or we can do a String Extension in Swift 4

    extension String {
        func getCharAtIndex(_ index: Int) -> Character {
            return self[self.index(self.startIndex, offsetBy: index)]
        }
    }
    

    USAGE:

    let foo = "ABC123"
    foo.getCharAtIndex(2) //C
    

提交回复
热议问题