×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strings.Count() Function with Examples

Golang | strings.Count() Function: Here, we are going to learn about the Count() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 15, 2021

strings.Count()

The Count() function is an inbuilt function of strings package which is used to count the number of non-overlapping instances of substring in the string. It accepts two parameters – the first parameter is the string in which we have to count the instances of the substring and the second parameter is the substring whose instances are to be count in the string. It returns an integer value. The result will be the total number of non-overlapping instances of substring in the string. If the substring is empty then it returns the number of Unicode code points in string +1.

Syntax

func Count(str, substr string) int

Parameters

  • str : String in which we have to count the number of non-overlapping instances of the substring.
  • substr : Substring to be checked.

Return Value

The return type of Count() function is an int, it returns the total number of non-overlapping instances of substr in the str (if substr is not empty).

Example 1

// Golang program to demonstrate the
// example of strings.Count() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Count("Hello, world!", "o"))
	fmt.Println(strings.Count("Hello, world!", "l"))
	fmt.Println(strings.Count("Hello, world!", "Hi"))
	fmt.Println(strings.Count("Hi guys, she said Hi to everyone.", "Hi"))
	fmt.Println(strings.Count("Hello, world!", ""))
}

Output:

2
3
0
2
14

Example 2

// Golang program to demonstrate the
// example of strings.Count() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str1 string = "Is are am. Is are am."
	var str2 string = "Hello, friends! How are you?"
	var substr string

	substr = "Is"

	var count = strings.Count(str1, substr)
	fmt.Printf("\"%s\" repeats %d times in \"%s\"\n", substr, count, str1)

	count = strings.Count(str2, substr)
	fmt.Printf("\"%s\" repeats %d times in \"%s\"\n", substr, count, str2)

	substr = "are"

	count = strings.Count(str1, substr)
	fmt.Printf("\"%s\" repeats %d times in \"%s\"\n", substr, count, str1)

	count = strings.Count(str2, substr)
	fmt.Printf("\"%s\" repeats %d times in \"%s\"\n", substr, count, str2)
}

Output:

"Is" repeats 2 times in "Is are am. Is are am."
"Is" repeats 0 times in "Hello, friends! How are you?"
"are" repeats 2 times in "Is are am. Is are am."
"are" repeats 1 times in "Hello, friends! How are you?"

Golang strings Package Functions »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.