如何计算字符串的长度?例如,我有一个定义如下的变量:

var test1: String = "Scott"

然而,我似乎找不到字符串的长度方法。


当前回答

test1.endIndex给出的结果与Swift 3上的test1.characters.count相同

其他回答

这里有一些比使用全局函数更短、更自然的方法:

aString.utf16count

我不知道它是否在beta 1中可用。但它肯定在beta 2中。

您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。

“string”.length//6

免责声明:我写了这个扩展

test1.characters.count

将获取字符串中字母/数字等的数量。

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(打印“13”)

在Swift 2.x中,以下是如何找到字符串的长度

let findLength = "This is a string of text"
findLength.characters.count

返回24

您可以使用str.utf8.count和str.utf16.count,我认为这是最好的解决方案