To get a character at a specific index in a string in Swift, you can use the subscript
syntax with the index.
In this example,
str
with a value of "Hello World"
.str
.let str = "Hello World"
let charAtIndex4 = str[str.index(str.startIndex, offsetBy: 4)]
print("Character at index 4: \(charAtIndex4)")
Character at index 4: o
In this example,
str
with a value of "Swift"
.str
.let str = "Swift"
let charAtIndex2 = str[str.index(str.startIndex, offsetBy: 2)]
print("Character at index 2: \(charAtIndex2)")
Character at index 2: i
In this tutorial, we learned How to get Character at Specific Index in String in Swift language with well detailed examples.