Learn about C Program to Search a String in the List of Strings in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
C Program to Search a String in the List of Strings
We’ll be working with two-dimensional strings in this program. The term “two-dimensional strings” refers to an array of strings. It’s comparable to a two-dimensional array, but it’s made up of strings.
We can read the string using gets(), fgets(), [n], and other methods. Following that, each string is compared to s1 (s1 is the string to search). If a string is discovered, strcmp() returns zero; otherwise, it returns non-zero. If we omit case sensitivity, then “Similar”, “similar”, and “SIMILAR” are all the same, and if you want to ignore case sensitivity in the program as well, you can use stricmp() or strcasecmp().
#include<stdio.h>
#include<string.h>
int main()
{
char str[20][50], s1[50];
int n, i, found=0;
printf("Enter how many string (names): ");
scanf("%d", &n);
printf("Enter %d strings:\n", n);
for(i=0; i<n; i++)
{
scanf("%s", str[i]);
}
printf("Enter a string to search: ");
scanf("%s", s1);
for(i=0; i<n; i++)
{
if(strcmp(s1, str[i]) == 0)
{
found=1;
printf("Found in row-%d\n", i+1);
}
}
if(found==0) printf("Not found");
return 0;
}
Output:
Enter 5 strings:
Similar
Geeks
Code
Learn
Practice
Enter a string to search: Learn
Found in row-4
Enter how many string (names): 5
Enter 5 strings:
Similar
Geeks
Code
Learn
Practice
Enter a string to search: See
Not found
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
Copy Input to Output Using C Programming
C Program For Pyramid String Pattern