Home  >  Article  >  Backend Development  >  How do you Reverse a String in Go while Handling Runes for Unicode Characters?

How do you Reverse a String in Go while Handling Runes for Unicode Characters?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 22:59:29149browse

How do you Reverse a String in Go while Handling Runes for Unicode Characters?

Reversing Strings in Go: Handling Runes and Unicode Characters

Manipulating strings in Go can pose challenges when working with Unicode characters, which are represented as runes. Unlike C, where strings are treated as character sequences, Go handles strings as vectors of bytes. To address this, we must convert between bytes and runes to perform character-level operations.

Let's examine the code you provided:

<code class="go">func inverte() {
    var strs, aux string

    // Generate 5 strings with random characters of sizes 100, 200, 300, 400, and 500
    for i := 1; i < 6; i++ {
        strs = randomString(i * 100)
        fmt.Print(strs)

        // Attempt to reverse the characters
        for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
           aux = strs[i2]
           strs[i2] = strs[j]
           strs[j] = aux
       }
   }
}</code>

The issue in your code arises from the assignment strs[i2] = strs[j], where strs[i2] and strs[j] are both bytes. However, to swap characters, you need to work with runes. To address this, you can convert the byte values to runes using the rune function:

<code class="go">for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
    r1 := rune(strs[i2])
    r2 := rune(strs[j])
    strs[i2] = byte(r2)
    strs[j] = byte(r1)
}</code>

By converting to runes, you can perform the character-level swapping operation correctly.

The above is the detailed content of How do you Reverse a String in Go while Handling Runes for Unicode Characters?. 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