Go Language - Program to Reverse a String

Example 1: Using the loop

//Go Program to reverse a string using loop
package main

import "fmt"

// Main function
func main() {

str1 := "Earth"
str2 := "moon"
fmt.Println(Reverse(str1))
fmt.Println(Reverse(str2))
}
func Reverse(str string) string {
var reverse string

// Code to reverse a string
for i := len(str) - 1; i >= 0; i-- {
reverse = reverse + string(str[i])
}

return reverse
}

Output:




Example 2: Using recursion

//Go Program to reverse a string using recursion
package main

import (
"fmt"
)

// Main function
func main() {

str1 := "Earth"
str2 := "moon"
fmt.Println(Reverse(str1))
fmt.Println(Reverse(str2))
}
func Reverse(str string) string {
return reverseText(str, len(str)-1)
}

// This is reversing the string elements recursively
func reverseText(text string, location int) string {
// Condition to stop the recursion process
if location >= 0 {
// Recursive method call
return string(text[location]) + reverseText(text, location-1)
}
return ""
}

Output:




Example 3: Using slice

//Go Program to reverse a string using slice
package main

import "fmt"

// Main function
func main() {

str1 := "Earth"
str2 := "I love my country"
fmt.Println(Reverse(str1))
fmt.Println(Reverse(str2))
}

//Function to reverse a string
func Reverse(str string) string {

//converting to slice of runes
strSlice := []rune(str)
length := len(strSlice)

for i := 0; i < (length / 2); i++ {
strSlice[i], strSlice[length-i-1] = strSlice[length-i-1], strSlice[i]
}
//converting back to string
return string(strSlice)
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete