To get a substring between two specific characters in Swift, you can use the substring(with:)
method along with range(of:)
to find the ranges of the characters.
In this example,
str
with a string value.range(of:)
method to find the ranges of the first and second specific characters.upperBound
of the range of the first character and the lowerBound
of the range of the second character to define the range for our substring.substring(with:)
method to get the substring within the defined range.import Foundation
let str = "Hello [World]"
if let startIndex = str.range(of: "[")?.upperBound,
let endIndex = str.range(of: "]")?.lowerBound {
let substring = str[startIndex..<endIndex]
print("Substring between brackets is: \(substring)")
}
Substring between brackets is: World
In this example,
str1
with a different value.range(of:)
method to find the ranges of the first and second specific characters.upperBound
of the range of the first character and the lowerBound
of the range of the second character to define the range for our substring.substring(with:)
method to get the substring within the defined range.import Foundation
let str1 = "Swift-(Programming)-Language"
if let startIndex = str1.range(of: "(")?.upperBound,
let endIndex = str1.range(of: ")")?.lowerBound {
let substring = str1[startIndex..<endIndex]
print("Substring between parentheses is: \(substring)")
}
Substring between parentheses is: Programming
In this tutorial, we learned How to get Substring between two Specific Characters in Swift language with well detailed examples.