获取字符串的长度 [英] Get the length of a String
问题描述
如何获得String
的长度?例如,我定义了一个变量,如:
How do you get the length of a String
? For example, I have a variable defined like:
var test1: String = "Scott"
但是,我似乎无法在字符串上找到长度方法.
However, I can't seem to find a length method on the string.
推荐答案
自 Swift 4+ 起
就是:
test1.count
出于原因.
(感谢 Martin R)
(Thanks to Martin R)
从 Swift 2 开始:
在 Swift 2 中,Apple 已将全局函数更改为协议扩展,即与符合协议的任何类型匹配的扩展.因此新的语法是:
With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:
test1.characters.count
(感谢 JohnDifoo 的提醒)
(Thanks to JohnDifool for the heads up)
从 Swift 1 开始
使用计数字符方法:
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
直接来自 Apple Swift 指南
right from the Apple Swift Guide
(注意,对于 Swift 1.2 之前的版本,这将是 countElements(unusualMenagerie)
)
(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie)
instead)
对于你的变量,它会是
length = count(test1) // was countElements in earlier versions of Swift
或者你可以使用 test1.utf16count
Or you can use test1.utf16count
这篇关于获取字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!