英文:
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)
}
- 从用户获取输入。
- 以空格为分隔符进行分割。
- 接下来做什么?
希望能对你有所帮助。
谢谢!
英文:
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, ))
}
- Took input from the user
- Split on the occurrence of white space.
- 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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论