Golang 将字符串中的每个单词的首字母大写

Golang 将字符串中的每个单词的首字母大写

Golang中的字符串是一系列字符的集合。由于Go中的字符串是不可变的,在它们被创建后不能修改。然而,通过连接或添加到现有字符串,可以创建新的字符串。作为Go中的内置类型,字符串类型可以像其他任何数据类型一样以多种方式使用。

语法

strings.Join(words,” ”)

使用join方法可以将字符串的切片与分隔符连接在一起。该函数需要两个参数:字符串的切片和分隔符字符串。它返回一个由切片元素组成的、由分隔符分隔的单个字符串。

strings.Fields(str)

Fields()函数返回一个子字符串的切片,该函数根据空白字符将字符串分为子字符串。用于分割字符串的空白字符在返回的切片中不存在。

strings.Title(word)

使用Title()函数将字符串中每个单词的首字母转换为大写,而剩余的字母转换为小写。

func append(slice, element_1, element_2…, element_N) []T

append函数用于向数组切片中添加值。它接受多个参数。第一个参数是要添加值的数组,后面是要添加的值。函数然后返回包含所有值的最终切片。

步骤

  • 步骤1 - 创建一个主包并声明fmt和strings包

  • 步骤2 - 创建一个主函数

  • 步骤3 - 使用内部函数从单词中切割第一个字符并将其大写

  • 步骤4 - 使用join或append函数将大写的字符与单词合并

  • 步骤5 - 打印输出

示例1

在这个示例中,我们将看到如何使用内置函数Fields()、Join()和Title()来大写每个单词的第一个字符。输出将是控制台上首字母大写的单词。

package main
import (
    "fmt"
    "unicode"
)

func main() {
    mystr := "hello, alexa!"  //create a string 
    fmt.Println("The original string given here is:", mystr)
    var output []rune    //create an output slice
    isWord := true
    for _, val := range mystr {
        if isWord && unicode.IsLetter(val) {  //check if character is a letter convert the first character to upper case
            output = append(output, unicode.ToUpper(val))
            isWord = false
        } else if !unicode.IsLetter(val) {
            isWord = true
            output = append(output, val)
        } else {
            output = append(output, val)
        }
    }
    fmt.Println("The string after its capitalization is:")
    fmt.Println(string(output))  //print the output with first letter as capitalized
}

输出

The original string given here is: hello, alexa!
The string after its capitalization is:
Hello, Alexa!

示例2

在这个示例中,我们将学习如何通过将字符串转换为切片来将字符串中每个单词的首字母大写。

package main
import (
    "fmt"
    "unicode"
)

func main() {
    mystr := "hello, alexa!"  //create a string 
    fmt.Println("The original string given here is:", mystr)
    var output []rune    //create an output slice
    isWord := true
    for _, val := range mystr {
        if isWord && unicode.IsLetter(val) {  //check if character is a letter convert the first character to upper case
            output = append(output, unicode.ToUpper(val))
            isWord = false
        } else if !unicode.IsLetter(val) {
            isWord = true
            output = append(output, val)
        } else {
            output = append(output, val)
        }
    }
    fmt.Println("The string after its capitalization is:")
    fmt.Println(string(output))  //print the output with first letter as capitalized
}

输出

The original string given here is: hello, alexa!
The string after its capitalization is:
Hello, Alexa!

结论

我们使用两个示例执行了将字符串中每个单词的首字母大写的程序。在第一个示例中,我们使用了内置函数;在第二个示例中,我们使用了Unicode包来将字符大写。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程