Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   






Count() FUNCTION


Count() Function


The Count() Function is used to count, how many times a substring is present in the String.


Example :



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


Output :



 The count of the substring is 1

In the above code, we have declared a String 'Hello Beautiful World' and assigned it to a variable 'x'.


x := "Hello Beautiful World"

java_Collections

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'.


y := strings.Count(x, "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'.


java_Collections

And thus prints the position.


fmt.Println("The count of the substring is ",y)

Output :



 The count of the substring is 1

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.


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


Output :



 The count of the substring is 2

And we got 2 occurrences of 'Beautiful' as output.