How to find Length of a String in swift with example

The string contains a group of characters.

Characters can be normal alphabets or Unicode characters.

The length of a string is a count of the number of characters in a string.

For example, If a string is “abc”, Then the length of a string is 3.

Length of a String in Swift

There are two types of a string. One is a String of normal alphabets without Unicode and emoji characters The second type of string contains Unicode characters.

There are multiple ways we can find the length of a string.

The string contains a count property that returns the number of characters in a string in the Swift 4 version.

if the String contains Unicode characters, the count property does not give the correct count.

You can use String.utf8.count and String.utf16.count for unicode characters count.

String.utf8.count: returns the unicode character with UTF-8 representation String.utf16.count: returns the unicode character with UTF-16 representation

Here is an example program to find character count in Swift

var name: String = "John"
var message: String = "Hello😀"

print(name.count) //4
print(name.utf8.count)//4
print(name.utf16.count)//4

print(message.count)//6
print(message.utf8.count)//9
print(message.utf16.count)//7

Similarly, You can use the String.characters.count property to count characters in a string for swift 2 and 3 versions.

unicodeScalars.count returns the Unicode characters count as 1.

Let’s seen an example count of Unicode characters count with different methods.

var str: String = "😀"

print(str.count) //1
print(str.unicodeScalars.count)//1
print(str.utf8.count) //4
print(str.utf16.count) //2

Conclusion

Learn How to find the number of characters in a String. It includes UTF8 and 16 character counts and codes.