How to Reverse A String in Golang

Sheeraz Gul Feb 12, 2024
  1. Reverse String in GoLang
  2. Using Iterative Method to Reverse a String
  3. Using Rune Slice to Reverse a String
  4. Using the strings Package to Reverse a String
  5. Conclusion
How to Reverse A String in Golang

This tutorial demonstrates how to reverse a string in GoLang.

Reverse String in GoLang

Reversing a string is an easy operation in GoLang. We can either swap the letters of the given string or create an empty string and add the letters of the given string from the end.

There are several methods commonly used to reverse a string. Let’s explore three approaches: the iterative method, the conversion to a rune slice, and the use of the strings package.

Using Iterative Method to Reverse a String

Reversing a string using iteration involves defining a function that accepts a string and returns a resultant string. The process includes iterating over the given string and prepending its characters to the resultant string.

Once the iteration is complete, the resultant string is returned.

Code Example:

package main

import "fmt"

func StringReverse(InputString string) (ResultString string) {

	for _, c := range InputString {
		ResultString = string(c) + ResultString
	}
	return
}

func main() {
	String1 := "Delftstack"
	fmt.Println("The result for", String1, "is: ", StringReverse(String1))
	String2 := "Delftsatck.com"
	fmt.Println("The result for", String2, "is: ", StringReverse(String2))
	String3 := "www.Delftsatck.com"
	fmt.Println("The result for", String3, "is: ", StringReverse(String3))
}

In this code, we’ve implemented a concise string reversal function named StringReverse. We use a for loop to iterate over each character in the input string.

Within the loop, we prepend each character to the ResultString, effectively reversing the order of the characters. The main function showcases the application of this reversal function to three example strings: "Delftstack", "Delftsatck.com", and "www.Delftsatck.com".

We print the reversed results for each input string using fmt.Println.

Output:

The result for Delftstack is:  kcatstfleD
The result for Delftsatck.com is:  moc.kctastfleD
The result for www.Delftsatck.com is:  moc.kctastfleD.www

The output demonstrates the effectiveness of our StringReverse function in reversing these strings, providing the reversed versions.

Using Rune Slice to Reverse a String

Converting the string to a rune slice allows for in-place modification, which is particularly useful when dealing with Unicode characters. This method involves defining a function, converting the given string to a rune slice, swapping elements in reverse order, and converting it back to a string.

Code Example:

package main

import "fmt"

func StringReverse(InputString string) string {
	ByteString := []rune(InputString)
	for x, y := 0, len(ByteString)-1; x < y; x, y = x+1, y-1 {
		ByteString[x], ByteString[y] = ByteString[y], ByteString[x]
	}
	return string(ByteString)
}

func main() {
	String1 := "Delftstack"
	fmt.Println("The result for", String1, "is: ", StringReverse(String1))
	String2 := "Delftsatck.com"
	fmt.Println("The result for", String2, "is: ", StringReverse(String2))
	String3 := "www.Delftsatck.com"
	fmt.Println("The result for", String3, "is: ", StringReverse(String3))
}

In this code, we’ve implemented a string reversal function named StringReverse using a rune slice. Within this function, we convert the input string to a slice of runes, denoted as ByteString.

Using a loop, we iterate over the slice, swapping the first and last elements, the second and second-to-last, and so forth, until the entire slice is reversed. Finally, we convert the reversed rune slice back to a string and return the result.

We print the reversed results for each input string using fmt.Println.

Output:

The result for Delftstack is:  kcatstfleD
The result for Delftsatck.com is:  moc.kctastfleD
The result for www.Delftsatck.com is:  moc.kctastfleD.www

The output demonstrates the effectiveness of our StringReverse function in reversing these strings, providing the reversed versions.

This method directly modifies the byte representation of the string, providing an alternative approach to string reversal in GoLang.

Using the strings Package to Reverse a String

Using the strings package in Go to reverse a string involves two key functions: Split and Join.

The Split function disassembles the input string into individual characters, creating a slice of strings. Subsequently, a loop is employed to reverse this slice, swapping characters from both ends towards the center.

Finally, the Join function concatenates the reversed characters into a single string.

Code Example:

package main

import (
	"fmt"
	"strings"
)

func StringReverse(inputString string) string {

	characters := strings.Split(inputString, "")

	for i, j := 0, len(characters)-1; i < j; i, j = i+1, j-1 {
		characters[i], characters[j] = characters[j], characters[i]
	}
	reversedString := strings.Join(characters, "")
	return reversedString
}

func main() {
	String1 := "Delftstack"
	fmt.Println("The result for", String1, "is: ", StringReverse(String1))

	String2 := "Delftsatck.com"
	fmt.Println("The result for", String2, "is: ", StringReverse(String2))

	String3 := "www.Delftsatck.com"
	fmt.Println("The result for", String3, "is: ", StringReverse(String3))
}

In this code, we’ve implemented a string reversal function named StringReverse using the strings package. First, we split the input string into individual characters, creating a slice of strings called characters.

We then use a loop to reverse this slice by swapping elements from both ends towards the center. Finally, we join the reversed characters back into a single string using strings.Join.

In the main function, we apply this reversal function to three example strings: "Delftstack", "Delftsatck.com", and www.Delftsatck.com". We print the reversed results for each input string using fmt.Println.

Output:

The result for Delftstack is: kcatstfleD
The result for Delftsatck.com is: moc.kctastfleD
The result for www.Delftsatck.com is: moc.kctastfleD.www

The output demonstrates the effectiveness of our StringReverse function in reversing these strings, providing the reversed versions.

In this example, the Split function separates the characters of the original string, the loop reverses the order of these characters, and the Join function combines them back into a reversed string.

Conclusion

In conclusion, we have explored three methods for reversing strings in GoLang. First, through the iterative method, we demonstrated a simple yet effective approach of iterating through the characters of a string and prepending them to a resultant string.

The second method involved using a rune slice for in-place modification, which is particularly useful when handling Unicode characters. Lastly, we employed the strings package, utilizing the Split and Join functions to disassemble and reassemble characters, effectively achieving string reversal.

Each method was applied to three example strings, showcasing the versatility of our reversal functions. The concise code and clear output demonstrate the efficiency and adaptability of these techniques for reversing strings in GoLang.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Go String