How to split a string into substrings of a specific length in Golang?

In Golang, you can split a string into substrings of a specific length using the following approach:

package main import ( "fmt" ) func splitString(s string, chunkSize int) []string { var result []string // Iterate through the string and split into chunks of specified length for i := 0; i < len(s); i += chunkSize { // Calculate the end index for the current chunk end := i + chunkSize // If the end index is greater than the string length, adjust it accordingly if end > len(s) { end = len(s) } // Append the current chunk to the result slice result = append(result, s[i:end]) } return result } func main() { str := "abcdefghij" chunkSize := 3 substrings := splitString(str, chunkSize) // Print the substrings for _, substr := range substrings { fmt.Println(substr) } }

The splitString function takes two parameters: the input string s and the desired chunkSize. It returns a slice of strings, where each element represents a substring of s with the specified chunkSize.

In the splitString function, we use a loop to iterate through the input string. Within each iteration, we calculate the end index for the current chunk by adding the chunkSize to the current index. If the end index is greater than the string length, we adjust it to prevent going out of bounds.

Finally, we append each chunk to the result slice and return it.

In the main function, we demonstrate the usage of the splitString function by splitting the string "abcdefghij" into substrings of size 3 and printing each substring. The output will be:

abc def ghi j