find the position of the first occurrence of a substring in a string in C
Code snippet on how to find the position of the first occurrence of a substring in a string in C
#include <stdio.h>
#include <string.h>
int main()
{
const char str[] = "GeeksforGeeks is a computer science portal";
const char ch = 'e';
char *ret;
ret = strchr(str, ch);
printf("String after |%c| is - |%s|\n",
ch, ret);
return(0);
}
This code first begins by including some libraries that are needed, namely stdio.h
and string.h
. Then in the main function, we have a const char
string where we store the input string and a const char
where we store the character which we want to find. We declare a char
pointer ret
. Then we call the strchr
function, which has the purpose of finding the position of the first occurrence of a substring in a string. The strchr function takes two parameters: the string from which we have to find the substring and the character we are looking for. Then the result of the function is stored in the ret
pointer. Lastly, we call the printf
function to print out the string after the character we were looking for.