Get the Nth character of a string in the Swift programming language


In this article, you will learn how to obtain the Nth character of a string.

You will use the index() method to get the Nth character of a string. This method will give you the position index of the given string.

How to use the Index() Method?

Let's look at an example of how to use the index() method

Algorithm

Step 1 − Prepare an input string.

Step 2 − Call the index() method with the target offset.

Step 3 − Use the position index as a subscript to the input string.

Step 4 − Store the Nth character.

Example

import Foundation
let string = "Tutorial Points"
let characterIndex = 4
let index = string.index(string.startIndex, offsetBy:
characterIndex)
let nthCharacter = string[index]
print("Character at \(characterIndex) is \(nthCharacter)")

Output

Character at 4 is r

Here are some recommended methods to get the Nth character of a string.

How to use the String Extension?

This is the most recommended way to get the Nth character from a string using an extension like below −

Example

import Foundation
extension String {
   subscript(_ characterIndex: Int) -> Character {
      return self[index(startIndex, offsetBy: characterIndex)]
   }
}
let string = "Tutorial Points"
let characterIndex = 9
let nthCharacter = string[characterIndex]
print("Character at \(characterIndex) is \(nthCharacter)")

Output

Character at 9 is P

Explanation

In this example, we created a simple extension to get the character at the given index. In the subscript() function, we are using the index() function with the argument characterIndex.

For example, if you want to get a string at an index instead of a character. You have to modify the code in the extension like the one below

import Foundation
extension String {
   subscript(_ characterIndex: Int) -> Self {
      return String(self[index(startIndex, offsetBy:
      characterIndex)])
   }
}

In the above example, the subscript function returns a string instead of a character.

Conclusion

Getting the Nth character of a string is a common practice in Swift. Many times, you will be required to get the character of a string.

Updated on: 02-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements