How to Count Leading Spaces in a Go String

To determine the number of leading spaces in a Go string, one effective method is to use the strings.TrimLeft() function. Here’s how you can implement it:

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

func main() {
	str := "   This is a string"
	fmt.Println(countLeadingSpaces(str)) // 3
}

The countLeadingSpaces() function works by trimming all leading spaces from the input string and then subtracting the length of the trimmed string from the original string’s length, thereby producing the number of leading spaces.

Alternatively, you can manually count the spaces by iterating over the string’s characters until encountering a non-space character:

go
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
}

In this method, a counter is increased for each space character until a non-space character appears. Both methods are effective for counting leading spaces in a string.

Thanks for reading, and happy coding!