Home >Backend Development >Golang >golang string to uppercase

golang string to uppercase

王林
王林Original
2023-05-13 10:20:08656browse

In Golang, it is very simple to convert a string into uppercase letters. You can use the ToUpper() function in the strings package.

The following is a sample code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello, world"
    fmt.Println("原字符串:", str)
    fmt.Println("转换后的字符串:", strings.ToUpper(str))
}

Output:

原字符串: hello, world
转换后的字符串: HELLO, WORLD

As can be seen, the ToUpper() function converts all letters in the string to uppercase and returns a new string. Original uppercase letters in the string are not affected.

It should be noted that the ToUpper() function can only recognize letters in the ASCII character set. If you want to convert characters in non-ASCII character sets to uppercase, you need to use the ToUpper() function in the unicode package.

If you need to convert specific parts of the string to uppercase, you can do this by slicing and splicing. For example:

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello, world"
    strList := strings.Split(str, " ")
    first := strings.ToUpper(string(strList[0][0])) // 将首字母大写
    rest := strList[0][1:] + " " + strings.ToUpper(strList[1])
    result := first + rest
    fmt.Println("转换后的字符串:", result)
}

Output:

转换后的字符串: Hello, WORLD

Use the Split() function to split the string into two parts, then process the first letter and the remaining parts respectively, and finally splice them into a new string.

In general, the string conversion operation in Golang is very simple. You only need to use the built-in ToUpper() function or manual splicing. In actual development, you may encounter some string encoding problems, which need to be handled according to specific circumstances.

The above is the detailed content of golang string to uppercase. 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