Write a C program that checks if a string (s2) is detected within another string
ID: 3681413 • Letter: W
Question
Write a C program that checks if a string (s2) is detected within another string (s1). For example, the string “hello” (s2) is within “abcdhelloworld” (s1). The output of the program should inform the user whether the string was detected and, if detected, display the position in s1.
Note: The two strings can be declared and initialized in your program.
#define SIZE 500
Example 1:
If char s1[SIZE] = "abcdhelloworld";
char s2[SIZE] = "hello";
then (below is to be displayed by your program)
s1 is abcdhelloworld
s2 is hello
The string was detected.
hello is found at position 5 in abcdhelloworld
Example 2:
If char s1[SIZE] = "This is an example";
char s2[SIZE] = "simple";
then (below is to be displayed by your program)
s1 is This is an example
s2 is simple
The string was not detected.
Explanation / Answer
#include <stdio.h>
#include <string.h>
int main()
{
//declaration of s1 and s2
char s1[] = "abcdhelloworld";
char s2[] = "hello";
//pointers for comparsion
char *p1, *p2, *p3;
int i=0,j=0,flag=0;
p1 = s1;
p2 = s2;
for(i = 0; i<strlen(s1); i++)
{
if(*p1 == *p2)
{
p3 = p1;
for(j = 0;j<strlen(s2);j++)
{
if(*p3 == *p2)
{
p3++;p2++;
}
else
break;
}
p2 = s2;
if(j == strlen(s2))
{
flag = 1;
printf("The string was detected.");
// hello is found at position 5 in abcdhelloworld
printf("%s is found at position %d in %s ",s2,i,s1);
}
}
p1++;
}
if(flag==0)
{
printf("s1 is %s",s1);
printf("s2 is %s",s2);
printf("The string was not detected");
}
return (0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.