Golang Program to divide a string in 'N' equal parts


In the Go programming language, strings are a built-in data type that represents sequences of characters. They are defined using double quotes (") and can contain any valid UniExample characters. When a string is divided into n equal pieces, n substrings of equal length are created. Using string splitting or string slicing techniques in programming languages, the substrings can be obtained. Let’s see the examples to understand the logic.

Method 1: Using for loop and built-in append function

In this method, a function called divideString is defined accepts two inputs, a string and an integer, and outputs a slice of strings that corresponds to the various components of the original string. In order to determine the size of each component, the function divides the string into integers. A for loop is then used to traverse through the string and extract the parts. With a sample string and an integer, the main function performs the divideString function and prints the parts that are produced.

Syntax

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable Examples and fmt helps in formatting input and output.

  • Step 2 − Define a function divideString that takes in two parameters: a string mystr and an integer size.

  • Step 3 − Create a variable parts of type []string to store the divided parts of the string.

  • Step 4 − Calculate the size of each part by using integer division len(str) /size.

  • Step 5 − Use a for loop to iterate through the string and extract the parts.

  • Step 6 − In each iteration, calculate the start and end index of the current part.The start index is i * partSize, where i is the current iteration number.

  • Step 7 − The end index is start + partSize, except for the last iteration where it is set to len(str).

  • Step 8 − Append the current part (str[start:end]) to the parts variable. After the for loop, return the parts variable.

  • Step 9 − In the main function, call the divideString function, passing in a sample string and an integer.

  • Step 10 − Print the resulting parts using fmt.Println(parts) where ln means new line.

  • Step 11 − This algorithm is splitting the string into n equal parts by using integer division and using a for loop to extract the parts of the string by using the calculated start and end index of each part.

Example

In the following example, we are going to Using for loop and built-in append function to divide a string in 'N' equal parts in golang

package main
import (
   "fmt"
)

func divideString(mystr string, size int) []string {
   var parts []string
   partSize := len(mystr) / size
   for i := 0; i < size; i++ {
      start := i * partSize
      end := start + partSize
      if i == size-1 {
         end = len(mystr)
      }
      parts = append(parts, mystr[start:end])
   }
   return parts
}

func main() {
   mystr := "Hello,alexa!" //create a string
   fmt.Println("The string given here is:")
   n_parts := divideString(mystr, 3)
   fmt.Println("The string after is converted to n equal parts:")
   fmt.Println(n_parts)  //print the string divided into n equal parts 
}

Output

The string given here is:
The string after is converted to n equal parts:
[Hell o,al exa!]

Method 2: Using len method

In this method we will learn how to divide a string in ‘N’ equal parts. This program helps to divide the string into n parts using a for loop after computing the part size using the math package's ceil function. The final output is showing using the fmt package.

Syntax

math.Ceil()

A floating-point number can be rounded up to the nearest integer using the ceiling approach.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable Examples and fmt helps in formatting input and output.

  • Step 2 − Create a function main and in that function and take as input the string and the n-th portion of the string as size.

  • Step 3 − By dividing the input string's length by size and rounding to the nearest whole number (using arithmetic), using the Ceil() method determine the size of each component.

  • Step 4 − Create a slice array from scratch to store the components of the input string.

  • Step 5 − Start at index 0 and iterate through the input string using a for loop.

  • Step 6 − Calculate the start and end index of the current part for each iteration of the loop by multiplying the current loop index by the part size, and change the end index if it exceeds the input string length.

  • Step 7 − Slice the input string using the start and end indices, then add the resulting component to the parts array.

  • Step 8 − Use another loop to output each component of the input string together with its index when the first one has finished.

  • Step 9 − Overall, the program makes use of the math and fmt packages in Golang, uses the ceil function to determine the number of partitions needed to split the string into n pieces, and uses the for loop to repeatedly cycle through the text. Using the fmt package, the final output is shown.

Example

In the following example, we are going to use len method to divide a string in 'N' equal parts in golang.

package main
import (
   "fmt"
   "math"
)

func main() {
   input_string := "Hello, alexa!" //create a string
   fmt.Println("The input string given here is:", input_string)
   size := 3
   fmt.Println("The string after getting divided into n equal parts is:")

   partSize := int(math.Ceil(float64(len(input_string)) / float64(size)))
   parts := make([][]rune, size)

   for i := 0; i < size; i++ {     //run a loop get the string in n equal parts
      start := i * partSize
      end := start + partSize
      if end > len(input_string) {
         end = len(input_string)
      }
      parts[i] = []rune(input_string)[start:end]
   }

   for i, part := range parts {
      fmt.Printf("Part %d: %s\n", i+1, string(part))
   }
}

Output

The input string given here is: Hello, alexa!
The string after getting divided into n equal parts is:
Part 1: Hello
Part 2: , ale
Part 3: xa!

Conclusion

We executed the program of dividing a string in n equal parts using two examples. In the first example we use the loop and built-in append function and in the second example we used the len method.

Updated on: 20-Feb-2023

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements