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 包來大寫字元。

更新於:2023年2月1日

6K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.