Finding the index of a character in a Swift string


In iOS app development, it is common to find the index of a character in a string. Based on the given index, you can perform different actions. In this article, you will see some examples of how to get the index of a character using the below functions −

  • firstIndex(of:)

  • firstIndex(where:)

  • range(of:)

All the above methods can be performed on a string value in different use cases.

Using the FirstIndex() Method

In Swift, you can use the firstIndex(of:) method to find the index of a character within a string. Here's an example −

Example

let inputString = "The quick brown fox jumps over the lazy dog"
let target: Character = "q"
if let index = inputString.firstIndex(of: target) {
   let distance = inputString.distance(from: inputString.startIndex, to: index)
   print("Input string: \(inputString)")
   print("Index of '\(target)' is: \(distance)")
} else {
   print("Character not found")
}

Output

Input string: The quick brown fox jumps over the lazy dog
Index of 'q' is: 4

The preceding code defines an input string called inputString and a target character for the first occurrence of the character "q" through the firstIndex(of:) method. If the character is found, the method returns an optional index value. This value is unwrapped and used to calculate the distance from the beginning of the string to the retrieved index using the distance(from:to:) method. If the character is not found, the code outputs a message saying so.

Using the FirstIndex(where:) Method

This method allows you to search for a character that matches a given condition, rather than a specific character. Here's an example −

Example

let inputString = "The quick brown fox jumps over the lazy dog"
let target: String = "b"
if let index = inputString.firstIndex(where: { $0.isLetter && $0.lowercased() == target }) {
   let distance = inputString.distance(from: inputString.startIndex, to: index)
   print("Input string: \(inputString)")
   print("Index of '\(target)' is: \(distance)")
} else {
   print("Character not found")
}

Output

Input string: The quick brown fox jumps over the lazy dog
Index of 'b' is: 10

In the above example, we are using the firstIndex(where:) method to find the target lowercase "b" in the input string. This method takes a closure to provide the conditions to check the use cases and returns a boolean value. If this returns true, you will get the index of character passed in the closure, otherwise returns nil. That’s why we are using the optional binding (if-let) here to get the index in a safe way.

After getting the index value, we are using the distance(from:to:) method to get the final index of the character in the input string.

Using the Range(of:) Method

This method allows you to find the range of a substring within a string. Here's an example.

Example

let inputString = "The quick brown fox jumps over the lazy dog"
let target: String = "quick"
if let range = inputString.range(of: target) {
   let startingIndex = inputString.distance(from: inputString.startIndex, to: range.lowerBound)
   let endingIndex = inputString.distance(from: inputString.startIndex, to: range.upperBound)
   print("Input string: \(inputString)")
   print("Starting index of '\(target)' is: \(startingIndex)")
   print("Ending index of '\(target)' is: \(endingIndex)")
} else {
   print("Character not found")
}

Output

Input string: The quick brown fox jumps over the lazy dog
Starting index of 'quick' is: 4
Ending index of 'quick' is: 9

In the preceding code, we use the range(of:) method to find out the range of the substring "quick" in the input string. The method returns an optional range value. This value is unwrapped and used to calculate the distance from the beginning of the string to the lower and upper bounds of the range through the distance(from:to:) method. If the substring is not found, the code outputs a message saying so.

Conclusion

In Swift, there are several methods you can use to find the index of a character within a string including, we used the below methods −

  • firstIndex(of:)

  • firstIndex(where:)

  • range(of:)

All the above methods can be used to get index of a character in an input string. Many times, we need to get an index of character in our iOS application to perform some operations. These methods can be used in different use cases.

In this article, you learned about each method and these use cases to get an index. All the methods returns optional value as an output and we can use the optional binding to get the index safely.

Updated on: 04-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements