{

How to get the nth character of a string in Swift example


 Swift nth character of  string literal Examples

Sometimes, It is required to get a particular character from a given string.

You can get using the index in a java programming language.

The same does not work in a swift

let message = "Hello world!"
print(message[0]) 

It throws an error main.swift:2:7: error: ‘subscript(:)’ is unavailable: cannot subscript String with an Int, use a String.Index instead. print(message[0]) ^~~~~~~~~~ Swift.String:3:12: note: ‘subscript(:)’ has been explicitly marked unavailable here public subscript(i: Int) -> Character { get }

Then, How to get a specific character from a given string.

There are multiple ways we can do

Find nth Character of a String in Swift example

  • Convert String to Array using constructor and use index.

This example converts a string to an Array using the constructor. The first character gets retrieved using the index Array[index] syntax.

Here is an example

let message = "Hello world!"
var first = Array(message)[0]
print(first)// H

You can also create an extension for the String class and provide an implementation for the subscript method.

extension String {
       subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] }

}
let message = "Hello world!"
print(message[0]) //H
print(message[8])// r
  • using String.index and String.startIndex

String.index function return the distance from the given index. Here is an example

let message = "Hello world!"

let index = message.index(message.startIndex, offsetBy: 0) 
print(message[index])// H
let index1 = message.index(message.startIndex, offsetBy: 1) 
print(message[index1])// e

How to get the First and last Characters of a String?

You can write the code as per the above methods.

There is a simple way to do it.

In the version below Swift 5, you can use String. characters class first and last properties

let message = "Hello world"
let first = message.characters.first // print(first) //H

let last = message.characters.last 
print(last)// d

In Swift 5, characters are not required. You can directly call first and last on String object.

let message = "Hello world"
let first = message.first
print(first) //H

let last = message.last 
print(last)// d

Conclusion

In this tutorial, Learned how to get first, nth and last character in Swift Programming examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.