To get all the possible K length substrings in Go, you can iterate through the string and extract substrings of length K.
In this example,
getKLengthSubstrings
that takes a string str
and an integer k
as parameters.substrings
to store the K length substrings.k
using slicing.substrings
slice.substrings
slice.main
function, we define a string str
and an integer k
with specific values.getKLengthSubstrings
function with str
and k
and store the result in the variable substrings
.substrings
to standard output.package main
import "fmt"
func getKLengthSubstrings(str string, k int) []string {
var substrings []string
for i := 0; i <= len(str)-k; i++ {
substrings = append(substrings, str[i:i+k])
}
return substrings
}
func main() {
str := "Hello World"
k := 3
substrings := getKLengthSubstrings(str, k)
fmt.Println("All K length substrings:", substrings)
}
All K length substrings: [Hel ell llo lo o W Wo Wor orl rld]
In this example,
getKLengthSubstrings
that takes a string str
and an integer k
as parameters.substrings
to store the K length substrings.k
using slicing.substrings
slice.substrings
slice.main
function, we define a string str
and an integer k
with specific values.getKLengthSubstrings
function with str
and k
and store the result in the variable substrings
.substrings
to standard output.package main
import "fmt"
func getKLengthSubstrings(str string, k int) []string {
var substrings []string
for i := 0; i <= len(str)-k; i++ {
substrings = append(substrings, str[i:i+k])
}
return substrings
}
func main() {
str := "Hello World"
k := 4
substrings := getKLengthSubstrings(str, k)
fmt.Println("All K length substrings:", substrings)
}
All K length substrings: [Hell ello llo lo W o Wo Wor Worl orld]
In this tutorial, we learned How to get all the possible K length Substrings in a String in Go language with well detailed examples.