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步 – 创建一个包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
在这个例子中,我们将学习如何通过将一个字符串转换为符文片,将字符串中每个单词的第一个字符大写。
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包来大写字符。