Golang strings.ContainsRune() Method

Golang strings.ContainsRune() is a built-in function that “checks whether the Unicode code point r is within the string”. To check the specified rune in Golang String, you can use the “ContainsRune()” function.

Syntax

func ContainsRune(s string, r rune) bool

Parameters

The function takes two parameters.

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

Example 1

package main

import (
  "fmt"
  "strings"
)

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

Output

true
false

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, the zerox string does not contain the 97 Unicode Point Rune because it does not have the character “a” in it. That is why it returns false.

Example 2

package main

import (
  "fmt"
  "strings"
)

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

Output

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. But, first, we have defined the three strings and then the three Runes.

Then, we check the rune against the string using ContainsRune() function and display the results by showing the string, rune, and result.

Leave a Comment

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