Latest Code Tutorials

Golang String ContainsRune() Function Example


Golang String ContainsRune() is an inbuilt function that checks whether the Unicode code point r is within the string. If you want to check the specified rune in Golang String, then use the Golang ContainsRune() function.

Golang String ContainsRune()

Golang String ContainsRune() function returns true if the given string contains the specified rune in it, or ContainsRune() function returns false if the given string does not include the specified rune. It is defined under the string package so, and you have to import string package in your program for accessing the ContainsRune function.


func ContainsRune(s string, r rune) bool


The function takes two parameters.

Here, the s is the string, and r is s rune. The return type of the function is bool.


// hello.go

package main

import (

func main() {
	// Finds whether a string contains a particular Unicode code point.
	// The code point for the lowercase letter "a", for example, is 97.
	fmt.Println(strings.ContainsRune("appdividend", 97))
	fmt.Println(strings.ContainsRune("zerox", 97))


go run hello.go

In the above example, the appdividend string contains the rune 97 because a’s Unicode code point is 97. So it returns true.

In the second example, zerox string does not contain the 97 Unicode Point Rune because it does not have character a in the string. That is why it returns false.

Example 2

// hello.go

package main

import (

func main() {

	// Creating and initializing a string
	// Using shorthand declaration
	s1 := "The Most Dangerous Game"
	s2 := "Quibi"
	s3 := "AppDividend!"

	// Creating and initializing rune
	var r1, r2, r3 rune
	r1 = 'R'
	r2 = 105
	r3 = 33

	// Check the given string
	// containing the rune
	// Using ContainsRune function
	res1 := strings.ContainsRune(s1, r1)
	res2 := strings.ContainsRune(s2, r2)
	res3 := strings.ContainsRune(s3, r3)

	// Display the results
	fmt.Printf("String 1: %s , Rune 1: %q , Present: %t",
		s1, r1, res1)

	fmt.Printf("\nString 2: %s , Rune 2: %q , Present: %t",
		s2, r2, res2)

	fmt.Printf("\nString 3: %s , Rune 3: %q , Present: %t",
		s3, r3, res3)



go run hello.go
String 1: The Most Dangerous Game , Rune 1: 'R' , Present: false
String 2: Quibi , Rune 2: 'i' , Present: true
String 3: AppDividend! , Rune 3: '!' , Present: true

The above example explains itself. First, we have defined the three strings and then three Runes.

Then we are checking the rune against string using ContainsRune() function and then display the results by displaying string, rune, and result.

Finally, Go strings.ContainsRune() function example is over.

See also

How To Sort Slice In Golang

How to compare two slices in Golang

Golang String Contains()

Golang String make()

Golang String ContainsAny()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.