Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

swift - 获取字符串的长度(Get the length of a String)

How do you get the length of a String ?

(你如何得到一个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.

(但是,我似乎无法在字符串上找到长度方法。)

  ask by Scott Walter translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Swift 5+:

(迅捷5+:)

test1.count

(Swift 5.0 strings can, in some ways, simply be treated as an array. Hence you can use .count or for example .first )

((在某些方面,Swift 5.0字符串可以简单地视为一个数组。因此,您可以使用.count或例如.first ))


As of Swift 4

(从Swift 4开始)

It's just:

(只是:)

test1.count

for reasons.

(原因。)

(Thanks to Martin R)

((感谢Martin R))

As of Swift 2:

(从Swift 2开始:)

With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol.

(在Swift 2中,Apple已将全局功能更改为协议扩展,这些扩展可与符合协议的任何类型匹配。)

Thus the new syntax is:

(因此,新语法为:)

test1.characters.count

(Thanks to JohnDifool for the heads up)

((感谢JohnDifool的注意))

As of Swift 1

(从Swift 1开始)

Use the count characters method:

(使用计数字符方法:)

let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has (count(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"

right from the Apple Swift Guide

(直接来自Apple Swift指南)

(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie) instead)

((请注意,对于早于1.2的Swift版本,它将countElements(unusualMenagerie) ))

for your variable, it would be

(对于您的变量,它将是)

length = count(test1) // was countElements in earlier versions of Swift

Or you can use test1.utf16count

(或者您可以使用test1.utf16count)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...