Golang in sixty seconds — Count occurrences in a string

Photo of abacus
Photo by luis arias on Unsplash

Did you ever want to quickly count how many times the letter s appears in Mississippi? Well Go has your back:

strings.Count("Mississippi", "s") // 4

One of the most common code golf challenges I've seen is to count the occurrences of a letter in a string and do something with the information. Let's change every letter the word “Mississippi” into the number of times it occurs in the word:

word := “Mississippi”
newWord := “”
for _, l := range word {
    newWord = newWord + strconv.Itoa(strings.Count(word, string(l)))
}
fmt.Println(newWord) // "14444444224"

Here we're looping over each rune (character) in the word, counting the number of times it occurs, converting that number to a string and appending it to the newWord string. You can try it out here

Richard Bell

Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.