This is a C Program to find the first occurence of the any character of String2 in string1 & also its position.
This program takes two strings as input and finds the first occurence of the any character of String2 in string1 & also its position.
1. Take two strings as input.
2. Compare both the strings using two pointers.
3. Print the character which matches first and its position.
Here is source code of the C Program to find the first occurence of the any character of String2 in string1 & also its position. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
/*
* C Program to Find the First Occurence of the any Character of
* String2 in string1 & also its Position
*/
#include <stdio.h>
void main()
{
char s1[50], s2[10];
int i, flag = 0;
char *ptr1, *ptr2;
printf("\nenter the string1:");
scanf(" %[^\n]s", s1);
printf("\nenter the string2:");
scanf(" %[^\n]s", s2);
/*COMPARING THE STRING1 CHARACTER BY CHARACTER WITH ALL CHARACTERS OF STRING1*/
for (i = 0, ptr1 = s1;*ptr1 != '\0';ptr1++)
{
i++;
for (ptr2 = s2; *ptr2 != '\0';ptr2++)
{
if (*ptr1 == *ptr2)
{
flag = 1;
break;
}
}
if (flag == 1)
break;
}
if (flag == 1)
printf("\nfirst occurance of character of string2 in string1 is at position:%d and character is %c", i, *ptr2);
else
printf("\nnone of the characters of string1 match with mone of characters of string2");
}
1. Take two strings as input and store it in the array’s s1[] and s2[].
2. Use pointers ptr1 and ptr2 to point the array’s s1[] and s2[] respectively.
3. Compare each character of the array s2[] with the array s1. Use the variable i to find the position.
4. Print the character which matches first and the variable i for the position.
enter the string1:C Programming Class enter the string2:rnp first occurance of character of string2 in string1 is at position:3 and character is p
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check Computer Science Books
- Check C Books
- Practice BCA MCQs
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos