Home >Backend Development >Golang >## How Can I Convert Lowercase Characters to Uppercase in a Go String?

## How Can I Convert Lowercase Characters to Uppercase in a Go String?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 02:02:02686browse

## How Can I Convert Lowercase Characters to Uppercase in a Go String?

Altering Strings in Go

Q: I want to convert lowercase characters to uppercase in a string, but Go throws an error: "cannot assign to new_str[i]". How can I achieve this?

A: Understanding Go String Immutability

In Go, strings are immutable, meaning once created, their contents cannot be modified. This behavior aligns with the Go Language Specification, which states:

"Strings are immutable: once created, it is impossible to change the contents of a string."

A: Working Around String Immutability

To modify a string in Go, you have two options:

  1. Cast the string to a []byte slice and alter the slice.
  2. Create a new string with the desired modifications.

A: Altering Strings Using []byte Slices

Here is a modified version of your code that uses a []byte slice to alter the characters.

<code class="go">package main

import (
    "bytes"
    "fmt"
)

func ToUpper(str string) string {
    strBytes := []byte(str)
    for i := 0; i < len(str); i++ {
        if str[i] >= 'a' && str[i] <= 'z' {
            chr := uint8(rune(str[i]) - 'a' + 'A')
            strBytes[i] = chr
        }
    }
    return string(strBytes)
}

func main() {
    fmt.Println(ToUpper("cdsrgGDH7865fxgh"))
}
</code>

The above is the detailed content of ## How Can I Convert Lowercase Characters to Uppercase in a Go String?. 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