如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
如何计算字符串的长度?例如,我有一个定义如下的变量:
var test1: String = "Scott"
然而,我似乎找不到字符串的长度方法。
当前回答
使用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 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 1.2起,utf16Count已删除。现在应该使用全局count()函数并传递字符串的UTF16视图。以下示例。。。
let string = "Some string"
count(string.utf16)
在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);
现在(在Swift 2.3中),如果您使用:
myString.characters.count
该方法将返回“Distance”类型,如果您需要该方法返回Integer,则应按如下方式键入cast:
var count = myString.characters.count as Int
您可以使用SwiftString(https://github.com/amayne/SwiftString)这样做。
“string”.length//6
免责声明:我写了这个扩展