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

var test1: String = "Scott"

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


当前回答

这是我最后做的

let replacementTextAsDecimal = Double(string)

if string.characters.count > 0 &&
    replacementTextAsDecimal == nil &&
    replacementTextHasDecimalSeparator == nil {
        return false
}

其他回答

斯威夫特4

“string”.count

;)

雨燕3

extension String {
    var length: Int {
        return self.characters.count
    }
}

用法

“string”.length

在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);

使用Xcode 6.4、Swift 1.2和iOS 8.4:

    //: Playground - noun: a place where people can play

    import UIKit

    var str = "  He\u{2606}  "
    count(str) // 7

    let length = count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())) as Int // 3
    println(length == 3) // true
var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

这将统计正则Swift字符串中的字符

countElements((newString as String))    

这将统计NSString中的字符

在swift4中,我一直使用string.count,直到今天我发现

string.endIndex.encodedOffset

是更好的替代方法,因为它更快-对于50000个字符,字符串大约比.count快6倍。.count取决于字符串长度,但.endIndex.encodedOffset不一样。

但有一个“不”。它对带有表情符号的字符串不好,它会给出错误的结果,所以只有count是正确的。