How to count leading spaces in a string in Go

The best way to count the number of spaces before the first non-space character of a string in Go is by using the strings.TrimLeft function as shown below:

func countLeadingSpaces(line string) int {
	return len(line) - len(strings.TrimLeft(line, " "))
}

func main() {
	str := "   This is a string"
	fmt.Println(countLeadingSpaces(str)) // 3
}
Run this example on the Go playground

The countLeadingSpaces function above trims all the leading space characters from the original string and subtracts the length of the result from the length of the original to derive the number of leading spaces.

Another option is to iterate over each character in the string and increment a counter until the first non space character is encountered:

func countLeadingSpaces(line string) int {
	count := 0
	for _, v := range line {
		if v == ' ' {
			count++
		} else {
			break
		}
	}

	return count
}

func main() {
	str := "   This is a string"
	fmt.Println(countLeadingSpaces(str)) // 3
}
Run this example on the Go playground

Thanks for reading, and happy coding!