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"
fmt.Println("["+spaceStr+"] has : ", countLeading(spaceStr, ' '), " leading spaces ")
threeZerosStr := "000 3 zeros"
fmt.Println("["+threeZerosStr+"] has : ", countLeading(threeZerosStr, '0'), " leading zeros ")
eightZerosStr := "00000000 8 zeros"
fmt.Println("["+eightZerosStr+"] has : ", countLeading(eightZerosStr, '0'), " leading zeros ")
poundStr := "## 2 hash symbols"
fmt.Println("["+poundStr+"] has : ", countLeading(poundStr, '#'), " leading # 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
https://socketloop.com/tutorials/golang-print-leading-padding-zero-or-spaces-in-fmt-printf
See also : Golang : Convert octal value to string to deal with leading zero problem
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k Golang : On lambda, anonymous, inline functions and function literals
+4.5k Fix sudo yum hang problem with no output or error messages
+31.4k Golang : convert(cast) bytes to string
+10.7k Golang : Execute function at intervals or after some delay
+19k Golang : How to read integer value from standard input ?
+6.2k Golang : Print how to use flag for your application example
+3.6k Golang : How to detect if a sentence ends with a punctuation?
+4.7k Golang : Fibonacci number generator examples
+25.1k error: trying to remove "yum", which is protected
+4.1k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+3.5k Golang : Display advertisement images or strings on random order