0

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

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
RISHI KHANNA
  • 354
  • 5
  • 23

2 Answers2

5

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.

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
0

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"
openwonk
  • 14,023
  • 7
  • 43
  • 39
  • 1
    The problem is by using `string(word[0])` you dropped support for utf-8. That's why the other response is using `[]rune(word)[0]`. Compare with greek perspective http://play.golang.org/p/bkk_XkhtJr – tomasz Jun 27 '15 at 17:14
  • That's fair. I don't often have to think of acronyms in non-ASCII terms... See updated answer and comments in code. I'd still recommend applying `strings.Title("...")` to ensure capitalization. – openwonk Jun 28 '15 at 00:51