How to find the index of rune in the string in Golang?


Golang offers many built-in functions and packages to perform string operations. One common operation is finding the index of a particular rune in the string. In this article, we will explore how to find the index of a rune in a string in Golang.

Rune in Golang is an alias for int32 and represents a Unicode code point. Each character in a string is a rune. The string package in Golang provides several functions for handling runes in a string.

Let's take a look at how to find the index of a rune in a string in Golang.

Using the strings.IndexRune() Function

Golang's standard library provides a built-in function strings.IndexRune(s string, r rune) int to find the index of a particular rune in a string. This function takes two arguments, the string to search in, and the rune to find, and returns the index of the first occurrence of the rune in the string. If the rune is not found in the string, the function returns -1.

Here's an example −

Example

package main

import (
   "fmt"
   "strings"
)

func main() {
   str := "Hello, World!"
   index := strings.IndexRune(str, 'W')
   fmt.Println(index)
}

Output

7

In this example, we have a string str with value "Hello, World!". We are using the strings.IndexRune() function to find the index of the rune 'W'. The function returns 7, which is the index of the first occurrence of 'W' in the string.

Using a Loop to Find the Index of Rune

Another approach to finding the index of a rune in a string is to loop through each character in the string and compare it with the rune. Once the rune is found, return the index.

Here's an example −

Example

package main

import "fmt"

func main() {
   str := "Hello, World!"
   r := 'W'
   index := -1

   for i, char := range str {
      if char == r {
         index = i
         break
      }
   }
   fmt.Println(index)
}

Output

7

In this example, we have a string str with value "Hello, World!" and a rune r with value 'W'. We are using a for loop to loop through each character in the string and compare it with the rune r. Once the rune is found, we break out of the loop and return the index.

Conclusion

Finding the index of a rune in a string is a common operation in Golang. The strings.IndexRune() function provides a simple and efficient way to find the index of a rune in a string. Alternatively, we can use a loop to find the index of the rune in the string.

Updated on: 18-Apr-2023

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements