# Golang : Count leading or ending zeros(any item of interest) example

Problem:

You want to count the number of leading spaces or zeros in a string such as

`000-123-456` , `____abc` ( _ = spaces)

or

ending hash and dollar symbols in a string such as

`1123###`, `CALLMEMAYBE\$\$\$`

How to calculate the number of item of interest in a string?

Solution:

In Golang, a string a can be treated like a slice(array). Use `for` loop to iterate over the string, scan for item of interest and increase the counter whenever a match is found.

Here is an example on how to count number of leading and ending item of interest in a string.

Here you go!

`````` package main

import (
"fmt"
"unicode/utf8"
)

func countLeading(str string, item rune) int {
counter := 0
for _, value := range str {
if value == item {
counter++
} else {
break
}
}
return counter
}

//https://www.socketloop.com/tutorials/golang-reverse-a-string-with-unicode

func Reverse(s string) string {
totalLength := len(s)
buffer := make([]byte, totalLength)
for i := 0; i < totalLength; {
r, size := utf8.DecodeRuneInString(s[i:])
i += size
utf8.EncodeRune(buffer[totalLength-i:], r)
}
return string(buffer)
}

func countBackward(str string, item rune) int {
// reverse str first
reversedStr := Reverse(str)

reverseCounter := 0
for _, value := range reversedStr {
if value == item {
reverseCounter++
} else {
break
}
}
return reverseCounter
}

func main() {

spaceStr := "  2 spaces"

threeZerosStr := "000 3 zeros"

eightZerosStr := "00000000 8 zeros"

poundStr := "## 2 hash symbols"

suffixPoundStr := "##\$ # CALLMEMAYBE ###"
fmt.Println("["+suffixPoundStr+"] has : ", countBackward(suffixPoundStr, '#'), " ending # symbols ")
}
``````

Output:

[ 2 spaces] has : 2 leading spaces

[000 3 zeros] has : 3 leading zeros

[00000000 8 zeros] has : 8 leading zeros

[## 2 hash symbols] has : 2 leading # symbols

[##\$ # CALLMEMAYBE ###] has : 3 ending # symbols

Notice that in the string `[##\$ # CALLMEMAYBE ###]` the leading `##\$` is ignored and not included in the calculation.

Hope this helps and happy coding!

References:

https://www.socketloop.com/tutorials/golang-reverse-a-string-with-unicode