Golang:给定句子的首字母缩写。

huangapple go评论84阅读模式
英文:

Golang: acronym of given sentence

问题

如何使用GO编程语言找到给定句子的首字母缩写。例如,"Hello, world!" 变成 "HW"。到目前为止,我尝试了以下方法:

package main

import (
    "bufio"
    "fmt"
    "strings"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("输入文本: ")
    text, _ := reader.ReadString('\n')
    words := strings.Split(text, " ")
    acronym := ""
    for _, word := range words {
        acronym += string(word[0])
    }
    fmt.Println(acronym)
}
  1. 从用户获取输入。
  2. 以空格为分隔符进行分割。
  3. 接下来做什么?

希望能对你有所帮助。

谢谢!

英文:

How to find, given a sentence, the acronym of that sentence using GO programming language. For example, “Hello, world!” becomes “HW”. So far I have tried splitting the sentence:

package main

import (
    "bufio"
    "fmt"
    "strings"
	"os"
)
func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Print(strings.Split(text," "))
	fmt.Print(strings.Index(text, ))
}
  1. Took input from the user
  2. Split on the occurrence of white space.
  3. What next?

Any help is appreciated.

Thanks

答案1

得分: 5

在你拆分字符串之后,你需要将每个单词的第一个字母添加到结果字符串中。

text := "Hello World"
words := strings.Split(text, " ")

res := ""

for _, word := range words {
    res = res + string([]rune(word)[0])
}

fmt.Println(res)

请注意,你可能需要添加一些检查来捕获输入为空的情况,这会导致strings.Split返回[""]

英文:

After you have split the strings you need to append the first letter of each word to your result string.

text := "Hello World"
words := strings.Split(text, " ")

res := ""

for _, word := range words {
	res = res + string([]rune(word)[0])
}

fmt.Println(res)

Note that you might need to add some checks to catch the case if the input is empty which results in a [""] from strings.Split.

答案2

得分: 0

同意第一个答案,但实现略有不同;请确保在代码开头导入"strings"

text := "holur stál fyrirtæki" // 假的制造商,"hollow steel company"
words := strings.Split(text, " ")

res := ""

for _, word := range words {
    // 在转换为字符串之前将其转换为[]rune以保留UTF8编码
    // 使用"strings"包中的"Title"确保首字母大写
    res += strings.Title(string([]rune(word)[0]))
}

fmt.Println(res) // => "HSF"

注意:以上代码是Go语言的实现,用于将字符串中每个单词的首字母转换为大写,并将结果连接起来。

英文:

Agree with first answer, but slightly different implementation; be sure to import "strings" at beginning of your code:

text := "holur stál fyrirtæki" // fake manufacturer, "hollow steel company"
words := strings.Split(text, " ")

res := ""

for _, word := range words {
    // Convert to []rune before string to preserve UTF8 encoding
    // Use "Title" from "strings" package to ensure capitalization of acronym
    res += strings.Title(string([]rune(word)[0]))
}

fmt.Println(res) // => "HSF"

huangapple
  • 本文由 发表于 2015年6月27日 14:45:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/31086007.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定