Go语言程序:将字符串中每个单词的首字母大写
在 Go 语言中,字符串是字符的集合。由于 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 − 创建一个 `main` 包并声明 `fmt` 和 `strings` 包
步骤 2 − 创建一个 `main` 函数
步骤 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
在这个示例中,我们将学习如何通过将字符串转换为 rune 切片来将字符串中每个单词的首字母大写。
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 包来大写字符。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP