Golang program to swapping pair of characters


A string in Golang is a collection of characters. Since strings in Go are immutable, they cannot be modified after they have been produced. Concatenating or adding to an existing string, however, enables the creation of new strings. A built-in type in Go, the string type can be used in a variety of ways much like any other data type. Let’s see how the logic can be executed. In this article, we will inculcate the ways to swap pair of characters in the string using different set of examples.

Syntax

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Method 1 : By converting the string to byte slice

Here, in increments of 2, the method iterates through the input string after converting it to a byte slice. Using a multiple assignment statement, it switches the current character with the following one after each iteration. After that, the obtained byte slice is changed back into a string and given back.

Algorithm

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

  • Step 2 − Create a function swap_pairs and in that function create a byte slice from the input string.

  • Step 3 − Set the value of a variable i to 0 and use a for loop to go through the bytes, increasing i by 2 each time.

  • Step 4 − Use a multiple assignment statement inside the for loop to swap the current character (at index i with the following character (at index i+1)).

  • Step 5 − Return the string-to-byte slice conversion after the for loop terminates and the output is printed on the console using fmt.Println() function where ln means new line.

  • Step 6 − It only iterates through the string once and executes the swap operation "in-place" on the byte slice, this approach makes it possible to efficiently swap pairs of characters in the input string.

Example

In this example we will see how to swap pair of characters by converting the string to byte.

package main
import (
   "fmt"
)

func swap_pairs(str string) string {
   b := []byte(str)  //convert the string to byte
   for i := 0; i < len(b)-1; i += 2 {
      b[i], b[i+1] = b[i+1], b[i] //swap the pair of characters
   }
   return string(b)  //return the swapped string
}

func main() {
	str := "hello" //create a string 
	fmt.Println("The string created here is:", str)
	fmt.Println("The string with characters swapped is:")
	fmt.Println(swap_pairs(str))   //print the swapped string on the screen 
}

Output

The string created here is: hello
The string with characters swapped is:
ehllo

Method 2: Using Recursion Method

In this example, we will see how to swap pair of characters using recursion. Recursion is used by the function to repeatedly swap the string's initial two characters, after which the remaining characters are passed on to the subsequent call. When the input string contains fewer than two characters, the recursion's base case, the string is returned in its original form. Each recursive call returns the string's first character concatenated with its second character, along with the remainder of the string that will be sent to the following recursive call. Let’s see the Example: and the algorithm to know its execution.

Algorithm

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

  • Step 2 − Create a function swap_pairs_recursive with one string parameter whose pair of character is to be swapped.

  • Step 3 − In the function, verify that the input string is only two characters or less. In that case, simply return the string.

  • Step 4 − Return the second character concatenated with the first character, concatenated with the outcome of executing swap_pairs_recursive on a substring of the input string beginning with the third character, if the input string is longer than 2 characters.

  • Step 5 − On the input string, call the swap_pairs_recursive function.

  • Step 6 − The function call's output should be printed using fmt.Println() function where ln means new line.

  • Step 7 − Recursion is used in this approach to transmit the remaining characters to the subsequent recursive call while repeatedly swapping the first two characters of the input string. Due to the several function calls and string concatenation required, it is less effective than the prior technique.

Example

In this example, we will see how to swap pair of characters using recursion.

package main
import (
   "fmt"
)

func swap_pairs_recursive(str string) string {
   if len(str) < 2 {
      return str //return the string if the length is less than 2
   }
   return str[1:2] + str[0:1] + swap_pairs_recursive(str[2:]) //swap the characters recursively
}

func main() {
   str := "hello" //create the string
   fmt.Println("The string created here is:", str)
   fmt.Println("The string with characters swapped is:")
   fmt.Println(swap_pairs_recursive(str)) //print the swapped string recursively
}

Output

The string created here is: hello
The string with characters swapped is:
ehllo

Conclusion

We executed the program of swapping pair of characters using two examples. In the first example we used the string to byte conversion and in the second example we used recursion to swap characters.

Updated on: 20-Feb-2023

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements