Get nth character of a string in Swift programming language

后端 未结 30 1973
一整个雨季
一整个雨季 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:44

    The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters. The variable length of a UTF character in memory makes jumping directly to a character impossible. That means you have to manually loop over the string each time.

    You can extend String to provide a method that will loop through the characters until your desired index

    extension String {
        func characterAtIndex(index: Int) -> Character? {
            var cur = 0
            for char in self {
                if cur == index {
                    return char
                }
                cur++
            }
            return nil
        }
    }
    
    myString.characterAtIndex(0)!
    

提交回复
热议问题