In this article, we will see how to split a string by its length in golang.

We can easily do this by using the slice expression. It represents a portion of the string s that starts at index i and ends at index j-1. It is commonly used for string manipulation operations such as extracting substrings and splitting strings into substrings.

Following is the example of how to split string into multiple strings based by the given length.

package main

import (

func main() {
    s := "abcdefghijk"
    n := 3
    result := []string{}
    for i := 0; i < len(s); i += n {
        end := i + n
        if end > len(s) {
            end = len(s)
        result = append(result, s[i:end])

In the above example we are using slice expression to extract the substring from a string.

This code will split the string s into substrings of length n and store them in a slice called result. The output will be [abc def ghi jk].

Categorized in:

Tagged in: