In Swift, you can use string slicing to get the first N characters from a string.
In this example,
str
with a string value of "Hello World"
.str.prefix(5)
to get the first 5 characters.let str = "Hello World"
let first5Chars = str.prefix(5)
print("First 5 characters of the string are: \(first5Chars)")
First 5 characters of the string are: Hello
In this example,
str
with a string value of "apple"
.str.prefix(3)
to get the first 3 characters.let str = "apple"
let first3Chars = str.prefix(3)
print("First 3 characters of the string are: \(first3Chars)")
First 3 characters of the string are: app
In this tutorial, we learned How to get First N Characters in String in Swift language with well detailed examples.