Write a program to search a character in a string using pointer in C language

 

#include <stdio.h>
#include<stdlib.h>

int main(void) 
{
    char *p;
    
    char key;
    int size,flag=0;
    int i;
    printf("Enter the size of string:\n");
    scanf("%d",&size);
    
    p=(char*)malloc(size+1);
    printf("Enter the string\n");
    scanf("%s",p);
    printf("Enter the character to search:\n");
    scanf(" %c", &key);
    
    for(i=0;*(p+i)!='\0';i++)
     {
         
         if(*(p+i)==key)
         {
             flag=1;
         printf("\n character %c found at %d position",*(p+i),i+1);
         break;
         }
     }
     if(flag==0)
     printf("\n character not found");
    
  return 0;
} 
 
 
output:
Enter the size of string:
 Enter the string
language 
 Enter the character to search:
g
 character g found at 4 position 


Explanation:

The program is to search a character in a string using a pointer in c language.
Observe the above program,
*p is taken as a pointer variable. Initially, *p will contain garbage value.
We have to allocate dynamic memory for a pointer variable p using the malloc function to take a string as input.
If you are not aware of how to use the malloc function, click on the below link.
 malloc function in c

 An integer variable "size", is taken as input to determine the size of the string.
p=(char*)malloc(size+1);
in the above syntax, memory is allocated for p.
As we know, at the end of every string, there is a by default null character. We have to allocate an extra 1byte for the null character. Hence (size+1) is used.
A integer variable key is taken as input, which is the search variable.
Inside the for loop, the first condition is applied in for loop syntax *(p+i)!='\0' the loop will run until null character comes. As we know, the last character is by default null character. 

The second condition is applied inside the for-loop block, if(*(p+i)==key) that means each character in the string one by one is compared with the key. When the comparison is found, control will come inside if block. Inside if block, the flag is set to 1, which was initialized as 0, printf statement is executed, further break keyword is executed to bring the control instantly outside the for-loop. 

Outside the for-loop, if the condition is applied flag==0, which means if the flag is equal to zero, characters is not found in the string. 

If the character is found, if-condition inside for-loop will be executed. Otherwise, if-condition outside for-loop will be executed.