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

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example