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
+8k Golang : Implementing class(object-oriented programming style)
+5.7k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+12.8k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+11.4k Golang : Gorilla web tool kit secure cookie example
+9.1k Golang : Accessing content anonymously with Tor
+6k Golang : Test input string for unicode example
+7.1k Golang : Check to see if *File is a file or directory
+4.1k Javascript : How to show different content with noscript?
+12.2k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+10k Golang : Convert file unix timestamp to UTC time example
+7.1k Android Studio : How to detect camera, activate and capture example
+11.6k Golang : Detect user location with HTML5 geo-location