search for a character in a string in Go
Code snippet on how to search for a character in a string in Go
package main
import "strings"
func main() {
str := "Hello GoLang!"
result := strings.IndexRune(str, 'G')
println(result)
}
This code will search for the character ‘G’ inside the given string “Hello GoLang!“. The code starts by importing the “strings” package from Go, which contains several useful functions related to string manipulation. Then, a new string is created with the text “Hello GoLang!“. The strings.IndexRune() function is used to search for the character ‘G’ inside the string. This function takes two parameters, the string and the character to be searched for, and returns the starting index of the character, if found. The result is then printed to the console. If ‘G’ is found, the output would be 6 as that is the starting index of ‘G’ inside the string. Otherwise, -1 will be printed.