OneBite.Dev - Coding blog in a bite size

search for a character in a string in C

Code snippet on how to search for a character in a string in C

 int findChar(const char *string, char target) {
  int i = 0;
  while (string[i] != '\0') {
    if (string[i] == target) {
      return i;
    }
    i++;
  }
  return -1;
}

The given code is written in C and is used for searching for a given character in a string. The code begins by declaring a function findChar which takes in two parameters: a character pointer string and the target character target. The i counter is initiated with a value of 0 and the loop begins. While the current character in the string doesn’t equal the null character (or the end of the string), the loop continues. Throughout the loop, the character stored in string[i] is checked against the target character. If the two are found to be identical, the index at which the character was found is returned as the result. If the target character isn’t found, the counter i is incremented and the loop continues. When the loop ends, if the desired character was not found, then -1 is returned.

c