Find the location of given Character in a String using Pointers

Get a String and a character then find where the character occurred first in the string.

Sample Input 1:

Hello l

Sample Output 1:

2

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

#include<stdio.h> int main() { //write your code here }

Program or Solution

				
			
					
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
	char *str;
	char s;
	int i;
	str=calloc(sizeof(char),50);
	fgets(str,50,stdin);
	scanf("%c",&s);
	
		
	for(i=0;i<strlen(str)-1;i++)
	{
			if(*(str+i)==s)
			{
				printf("character found at %d",i);
				return 0;
			}
		
	}
	printf("character not found");
	return 0;
}

	

			
				
			

Program Explanation

Get a String using fgets() function.

Str -> reads the string and stores it in str.

50 -> reads maximum of 50 characters stdin-> reads character from keyboard read character s using scanf() for loop iterates and check each character whether it is s.

if(str[i]==s) then prints I, else moves to next character.

Comments