To get all possible substrings of a string in Swift, you can use nested loops to iterate through each combination of start and end indices.
In this example,
str
with a value of 'Hello'
.substrings
to store all substrings.subscript
notation and add it to the substrings
array.substrings
array.let str = "Hello"
var substrings: [String] = []
for i in 0..<str.count {
for j in i + 1...str.count {
let substring = str[str.index(str.startIndex, offsetBy: i)..<str.index(str.startIndex, offsetBy: j)]
substrings.append(String(substring))
}
}
print("All substrings:", substrings)
All substrings: ["H", "He", "Hel", "Hell", "Hello", "e", "el", "ell", "ello", "l", "ll", "llo", "l", "lo", "o"]
In this tutorial, we learned How to get all the possible Substrings of a String in Swift language with well detailed examples.