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

var test1: String = "Scott"

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


当前回答

在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

现在(在Swift 2.3中),如果您使用:

myString.characters.count 

该方法将返回“Distance”类型,如果您需要该方法返回Integer,则应按如下方式键入cast:

var count = myString.characters.count as Int

在Swift 4.2和Xcode 10.1中

在Swift中,字符串可以被视为单个字符的数组。所以字符串中的每个字符就像数组中的一个元素。要获取字符串的长度,请使用StringName.count属性。

在Swift中

yourStringName.character.count属性已弃用。所以直接使用strLength.count属性。

let strLength = "This is my string"
print(strLength.count)
//print(strLength.characters.count) //Error: 'characters' is deprecated: Please use String or Substring directly

如果目标C

NSString *myString = @"Hello World";
NSLog(@"%lu", [myString length]); // 11

如果您正在寻找一种更简洁的方法来获取字符串长度,请检查这个库,它有一系列对Swift内置类的扩展http://www.dollarswift.org/#length

使用这个库,您只需执行“Some Str”.length

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