Example:
Input string: I love programming.
Input character: o
Output: 3
Required knowledge
Basic C programming, If else, Loop, StringProgram 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
/** Function declaration */
int indexOf(const char * text, const char toFind);
int main()
{
char text[MAX_SIZE];
char toFind;
int index;
/*
* Reads a string from user and character to be searched
*/
printf("Enter any string: ");
gets(text);
printf("Enter character to be searched: ");
toFind = getchar();
index = indexOf(text, toFind);
if(index == -1)
{
printf("'%c' not found.", toFind);
}
else
{
printf("Index of '%c' is %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 * text, const char toFind)
{
int index = -1; // Assumes that the character doesn't exists
int i, len;
len = strlen(text);
for(i=0; i<len; i++)
{
if(text[i] == toFind)
{
index = i;
break;
}
}
return index;
}
Output
Enter any string: I love programming.
Enter character to be searched: o
Index of 'o' is 3.
Enter character to be searched: o
Index of 'o' is 3.
Note: Index returned by the function indexOf() is zero based index.
Happy coding ;)
You may also like
- String programming exercises and solution.
- C program to find last occurrence of a character in a string.
- C program to count occurrences of a character in a given string.
- C program to remove first occurrence of a character from the string.
- C program to remove last occurrence of a character from the string.
- C program to remove all occurrences of a character from the string.
- C program to find length of a string.
- C program to copy one string to another string.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find total number of words in a string.
- C program to find frequency of each character in a string.