To get all possible K-length substrings in a string in Swift, you can use a combination of loops and the String method 'index'. This approach allows you to generate all substrings of a specified length from the given string.
In this example,
str
with a value of "Hello World"
.k
with a value of 3
, representing the length of the substrings we want to extract.substrings
of type [String]
to store the resulting substrings.for
loop to iterate through the string. The loop variable i
starts from 0
and goes up to str.count - k
to ensure we don't go out of bounds.str.index(str.startIndex, offsetBy: i)
and str.index(str.startIndex, offsetBy: i + k)
respectively.str
and append it to the substrings
array.substrings
array to the standard output.let str = "Hello World"
let k = 3
var substrings = [String]()
for i in 0..<(str.count - k + 1) {
let start = str.index(str.startIndex, offsetBy: i)
let end = str.index(start, offsetBy: k)
let substring = String(str[start..<end])
substrings.append(substring)
}
for substring in substrings {
print(substring)
}
Hel ell llo lo o W Wo Wor orl rld
In this example,
str
with a value of "Swift Programming"
.k
with a value of 4
, representing the length of the substrings we want to extract.substrings
of type [String]
to store the resulting substrings.for
loop to iterate through the string. The loop variable i
starts from 0
and goes up to str.count - k
to ensure we don't go out of bounds.str.index(str.startIndex, offsetBy: i)
and str.index(str.startIndex, offsetBy: i + k)
respectively.str
and append it to the substrings
array.substrings
array to the standard output.let str = "Swift Programming"
let k = 4
var substrings = [String]()
for i in 0..<(str.count - k + 1) {
let start = str.index(str.startIndex, offsetBy: i)
let end = str.index(start, offsetBy: k)
let substring = String(str[start..<end])
substrings.append(substring)
}
for substring in substrings {
print(substring)
}
Swif wift ift ft P t Pr Pro Prog rogr ogra gram ramm ammi mmin ming
In this tutorial, we learned How to get all the possible K length Substrings in a String in Swift language with well detailed examples.