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

var test1: String = "Scott"

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


当前回答

var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

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

countElements((newString as String))    

这将统计NSString中的字符

其他回答

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

雨燕1.1

extension String {
    var length: Int { return countElements(self) }  // 
}

雨燕1.2

extension String {
    var length: Int { return count(self)         }  // 
}

斯威夫特2.0

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

雨燕4.2

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

let str = "Hello"
let count = str.length    // returns 5 (Int)

只需写一个扩展就可以得到长度:

extension String {
    // MARK: Use if it's Swift 2
    func stringLength(str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 3
    func stringLength(_ str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 4
    func stringLength(_ str: String) -> Int {
        return str.count
    }
}

从文本视图或文本字段获取字符串值:

let textlengthstring = (yourtextview?.text)! as String

查找字符串中的字符数:

let numberOfChars = textlength.characters.count