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

var test1: String = "Scott"

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


当前回答

test1.characters.count

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

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(打印“13”)

其他回答

在Swift 4.1和Xcode 9.4.1中

在Objective c和Swift中获取长度是不同的。在Obj-c中我们使用长度属性,但在Swift中我们使用计数属性

例子:

//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)

//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);

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

为Xcode 6 beta 4更新,更改方法utf16count-->utf16count

 var test1: String = "Scott"
 var length =  test1.utf16Count

Or

 var test1: String = "Scott"
 var length = test1.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)

Swift 2.0版本:获取计数:yourString.text.characters.count

有趣的有用示例是在UITextView中显示某个数字(例如150)的字符倒计时:

func textViewDidChange(textView: UITextView) {
    yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}

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

“string”.length//6

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