Get the nth character of a string in Swift
In this tutorial, we will work on the task of getting the nth character from a given string as the title says it all, to retrieve a particular character present at a specific position.
Example
Given a string, CodeSpeedy we need to find its 2nd character.
The output must result in the character d starting the counting from 0, we know that the second character would be d. We are going to find it in Swift programming.
Implementation
There is a method in Swift which is known as index(), which functions to easily access and retrieve data from a string. The syntax for the same would be-
string.index()
To get this task done, we can approach the problem by following the steps as-
- Create a string.
- Define n.
- Invoke the function index(), which takes string.startIndex and offset indexnumber as parameter and stores the value in n.
- Use n to find the character at n in any string.
- Print the character.
Here’s the snippet part-
let str = "CodeSpeedy"
let indexnumber = 2
let n = str.index(str.startIndex, offsetBy:indexnumber)
let character = str[n]
print("Character at \(indexnumber) in \(str) is \(character)")Output- Character at 2 in CodeSpeedy is d
So here we have fetched the nth character from a string in Swift using indexing.
Leave a Reply