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
+7.7k Golang : HttpRouter multiplexer routing example
+17.1k Golang : delete and modify XML file content
+4.5k Nginx and PageSpeed build from source CentOS example
+18.2k Unmarshal/Load CSV record into struct in Go
+6.5k Fix sudo yum hang problem with no output or error messages
+11.8k Golang : List running EC2 instances and descriptions
+7.2k SSL : How to check if current certificate is sha1 or sha2 from command line
+31.1k Golang : Convert an image file to []byte
+6.8k Golang : Of hash table and hash map
+25.7k Golang : Convert(cast) string to uint8 type and back to string
+17.2k Convert JSON to CSV in Golang
+21.7k Golang : Print leading(padding) zero or spaces in fmt.Printf?