OneBite.Dev - Coding blog in a bite size

find the first occurrence of a character in a string in Go

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

  func IndexInString(str string, char byte) int { 
    for i := 0; i < len(str); i++ { 
      if str[i] == char { 
        return i 
      } 
    } 
    return -1 
  }

This code is written in the Go programming language, and it is designed to find the first occurrence of a character in a given string. It begins by defining a function called IndexInString that takes two arguments: a string and a single byte (a character).

Next, the code iterates over every element in the string using a for loop, and for every element, it checks whether the character given is equal to the current element in the string. If it is, then it returns the index of the current element. Otherwise, the loop continues until all elements are checked.

Finally, if the character is not found in the string, then the code returns -1. This lets the user know that the character was not found in the string.

go