The Count() Function is used to count, how many times a substring is present in the String.
package main import "fmt" import "strings" func main() { x := "Hello Beautiful World" y := strings.Count(x, "Beautiful") fmt.Println("The count of the substring is ",y) }
In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.
And we would be searching the substring 'Beautiful', and count how many times it is present in the String, 'Hello Beautiful World'.
So, we have used the 'Count()' Function to count for the substring 'Beautiful'.
And in this case the substring 'Beautiful' is present just once. So, we got the count as 1.
And the count (i.e. 1) is stored in variable 'y'.
And thus prints the position.
Now, let us say you have the below String,
"The Beautiful world is Beautiful indeed"
So there are two occurrence of 'Beautiful'.
Let us see with the below example.
package main import "fmt" import "strings" func main() { x := "The Beautiful world is Beautiful indeed" y := strings.Count(x, "Beautiful") fmt.Println("The count of the substring is ",y) }
And we got 2 occurrences of 'Beautiful' as output.