OneBite.Dev - Coding blog in a bite size

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

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

#include <stdio.h>
#include <string.h>

int main() { 
  char string[] = "Hello World"; 
  char character = 'o'; 
  int i; 

  for (i = 0; i < strlen(string); i++) { 
    if (string[i] == character) { 
      printf("'o' found at index %d", i); 
      break; 
    } 
  } 
  return 0; 
} 

This code finds the first occurrence of a character in a string in C. It starts by declaring a string and a character that needs to be found. Then it has a for-loop to traverse the string and check if the character and element at the current index are the same. If it finds a match, it will print the index at which it found it and break the loop. Lastly, the code will return 0 and the program will terminate.

c