C Program to Search a String in the List of Strings

Write a C program to search a string in the list of strings. Take input from the user. In this program, we will use two-dimensional strings. Two-dimensional strings mean the array of strings. It is similar to the two-dimensional array but it is a collection of strings. Prerequisites:- 2d array of strings in C

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)
       printf("Found in row-%d\n", i+1);

   if(found==0) printf("Not found");
   return 0;

Output for the different test-cases:-

Enter how many string (names): 5
Enter 5 strings:
Enter a string to search: Python
Found in row-3

Enter how many string (names): 3
Enter 3 strings:
Enter string to search: Java
Not found

C program to search a string in the list of strings, In this program first, we take input from user. To read the string we can use gets(), fgets(), [^\n] and other methods. But you may get different behavior of the program.

Later each string is compared with s1 (s1 is the string to search). If string is found then strcmp() returns zero, otherwise non-zero. Finally, we got the result.

If we ignore the case sensitivity then “Python”, “python” and “PYTHON” all are the same, and If you want to ignore this case sensitivity also in the program then you can use stricmp() or strcasecmp().

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Similar C programming examples on Arrays

Leave a Comment

Your email address will not be published. Required fields are marked *