OneBite.Dev - Coding blog in a bite size

Find The First Occurrence Of A Character In A String In Swift

Code snippet for how to Find The First Occurrence Of A Character In A String In Swift with sample and detail explanation

When working with programming languages like Swift, it’s often necessary to find the location of a specific character in a string. In this article, you will learn how to find the first occurrence of a character in a string using Swift.

Code Snippet: Finding a Character in a String

Here’s a simple way to find the first occurrence of a character in a string, using the firstIndex(of:) method in Swift.

let str = "Hello, World!"
let index = str.firstIndex(of: ",") 
if let index = index {
  let position = str.distance(from: str.startIndex, to: index)
  print("The comma is at position \(position)")
} else {
  print("The comma is not in the string")
}

Code Explanation: Finding a Character in a String

Now, let’s break down the code above to understand how it works.

The first line of the code creates a string str with the value “Hello, World!“.

let str = "Hello, World!"

The second line tries to find the first index of the comma character in the string str, and assign it to the constant index. The firstIndex(of:) method returns an optional String.Index, because the character may not be found in the string.

let index = str.firstIndex(of: ",") 

The subsequent lines of code deal with the possibility that the character may not be found. If index is nil, then the character was not found in the string. Otherwise, index is the position of the character in the string.

if let index = index {
  let position = str.distance(from: str.startIndex, to: index)
  print("The comma is at position \(position)")
} else {
  print("The comma is not in the string")
}

Here the if let syntax is used to unwrap the optional index. Once we have the unwrapped index, we calculate its position by using str.distance(from:to:). The distance method returns the number of steps to get from one index to another, essentially finding the character’s position.

By running the code, it will provide the output: “The comma is at position 5”, indicating that the first occurrence of the comma character ’,’ is at index 5 in the string “Hello, World!“.

swift