How to count the white spaces in a string in Go

1 Answer

0 votes
package main

import (
	"fmt"
	"unicode"
)

func countWhitespaceCharacters(str string) int {
	count := 0
	length := len(str)

	for i := 0; i < length; i++ {
		if unicode.IsSpace(rune(str[i])) {
			count++
		}
	}

	return count
}

func main() {
	str := "Golang \n  Programming \r Language \t "

	fmt.Println("Total white spaces:", countWhitespaceCharacters(str))
}


/*
run:

Total white spaces: 10

*/

 



answered Oct 20, 2024 by avibootz

Related questions

1 answer 170 views
2 answers 206 views
1 answer 111 views
1 answer 123 views
1 answer 106 views
...