OneBite.Dev - Coding blog in a bite size

find the position of the first occurrence of a substring in a string in Go

Code snippet on how to find the position of the first occurrence of a substring in a string in Go

index := strings.Index(string1, string2) 

This code finds the position of the first occurrence of a substring, string2, in a string, string1, using the strings.Index() function from the strings package in Go. The Index() function returns the index of the first occurrence of string2 in string1 as an int. If string2 is not found in string1, then it returns -1.

This code first declares a variable index and assigns it the value of the result of the Index() function. The Index() function takes two arguments, the main string, string1, and the substring you are looking for, string2. The function looks for the position of the first occurrence of string2 in string1 and returns that position as an int value, which is stored in the index variable.

go