Home >Backend Development >Golang >How to Reverse a String in Go?

How to Reverse a String in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 03:19:25408browse

How to Reverse a String in Go?

How to Flip a String's Characters in Go

In Go, there's a way to reverse the order of characters in a string. Here's how:

1. Represent the String as Runes:

In Go, Unicode characters are represented by runes, a type similar to integers. So, let's first convert the string into a slice of runes using the []rune(s) syntax.

2. Create a Helper Function:

Define a function called Reverse that takes a string parameter.

3. Iterate over the Rune Slice:

Use a for loop that starts at the beginning (i) and the end (j) of the rune slice. While i is less than j, increment i and decrement j by 1, swapping the values at those indices.

4. Return the Reversed String:

Convert the rune slice back into a string using the string(runes) syntax, and return it.

5. Code Example:

Here's an implementation of the Reverse function:

func Reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

Now, you can simply call the Reverse function on any string to get its reversed character order.

The above is the detailed content of How to Reverse a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn