¿Cómo invertir una string en Golang?

Dada una string y la tarea es invertir la string. Aquí están algunos ejemplos.

Enfoque 1: invierta la string intercambiando las letras, como la primera con la última y la segunda con la penúltima y así sucesivamente.

Ejemplo:

// Golang program to reverse a string
package main
  
// importing fmt
import "fmt"
  
// function, which takes a string as
// argument and return the reverse of string.
func reverse(s string) string {
    rns := []rune(s) // convert to rune
    for i, j := 0, len(rns)-1; i < j; i, j = i+1, j-1 {
  
        // swap the letters of the string,
        // like first with last and so on.
        rns[i], rns[j] = rns[j], rns[i]
    }
  
    // return the reversed string.
    return string(rns)
}
  
func main() {
  
    // Reversing the string.
    str := "Geeks"
  
    // returns the reversed string.
    strRev := reverse(str)
    fmt.Println(str)
    fmt.Println(strRev)
}

Producción:

Geeks
skeeG

Enfoque 2: este ejemplo declara una string vacía y luego comienza a agregar los caracteres desde el final, uno por uno.

Ejemplo:

// Golang program to reverse a string
package main
  
// importing fmt
import "fmt"
  
// function, which takes a string as
// argument and return the reverse of string.
func reverse(str string) (result string) {
    for _, v := range str {
        result = string(v) + result
    }
    return
}
  
func main() {
  
    // Reversing the string.
    str := "Geeks"
  
    // returns the reversed string.
    strRev := reverse(str)
    fmt.Println(str)
    fmt.Println(strRev)
}

Producción:

Geeks
skeeG

Publicación traducida automáticamente

Artículo escrito por PranchalKatiyar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *