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.
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.
In swift4 I have always used
string.count
till today I have found thatis the better substitution because it is faster - for 50 000 characters string is about 6 time faster than
.count
. The.count
depends on the string length but.endIndex.encodedOffset
doesn't.But there is one NO. It is not good for strings with emojis, it will give wrong result, so only
.count
is correct.will get you the number of letters/numbers etc in your string.
ex:
(prints "13")
TLDR:
For Swift 2.0 and 3.0, use
test1.characters.count
. But, there are a few things you should know. So, read on.Counting characters in Swift
Before Swift 2.0,
count
was a global function. As of Swift 2.0, it can be called as a member function.It will return the actual number of Unicode characters in a
String
, so it's the most correct alternative in the sense that, if you'd print the string and count characters by hand, you'd get the same result.However, because of the way
Strings
are implemented in Swift, characters don't always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages.For example, you can also use
test1.utf16.count
But, as noted below, the returned value is not guaranteed to be the same as that of calling
count
oncharacters
.From the language reference:
An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character, as pointed out by n00neimp0rtant in the comments.
Swift 4
"string".count
;)
Swift 3
usage
"string".length
You could try like this
Get string value from your textview or textfield:
Find the count of the characters in the string: