String Exercises
Write a C program to input any string from user and find the first occurrence of a given character in the string. How to find the first occurrence of a given character in a string in C programming. Logic to find first occurrence of a character in a string in C programming.
Required knowledge
Basic C programming, C for loop, Array, Pointer, functions, Strings
Logic to find first occurrence of a character in given string
Below is the step by step descriptive logic to get index of first occurrence of a character in a given string.
- Input string from user, store it in some variable say str.
- Run a loop from start character of the string to end character.
- Check if current character is matched with the search character. If match is found then terminate the above loop and return current character index.
Program to find first occurrence of character in string
/** * C program to find the first occurrence of a character in a string */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 // Maximum string size /* Function declaration */ int indexOf(const char * str, const char toFind); int main() { char str[MAX_SIZE]; char toFind; int index; /* Input string from user and character to be searched */ printf("Enter any string: "); gets(str); printf("Enter character to be searched: "); toFind = getchar(); index = indexOf(str, toFind); if(index == -1) printf("'%c' not found.", toFind); else printf("'%c' is found at index %d.", toFind, index); return 0; } /** * Returns the first index of the given character toFind in the string. * If returns -1 if the given character toFind does not exists in the string. */ int indexOf(const char * str, const char toFind) { int i = 0; while(str[i] != '\0') { if(str[i] == toFind) return i; i++; } // Return -1 as character not found return -1; }
Note: Index returned by the function indexOf() is zero based index.
You can also use pointer based string accessing in indexOf() function. Let me re-write the above indexOf() function with pointer based string accessing instead of indexed based accessing.
int indexOf(const char * str, const char toFind) { int i = 0; while(*str) { if(*str == toFind) return i; i++; str++; } // Return -1 as character not found return -1; }