January 18, 2025

Develop a C Program to Search a String in an Array

Let us play with Strings, String array in C. Let us go with simple examples. These examples are required for the major task : search a string in an array.

1: Compare 2 strings

#include <stdio.h>
#include <string.h>

int main()
{
    
    char name[] = "Suresh";
    char friendName[] = "Suresh";
    if(strcmp(name, friendName)==0){
        printf("Names are equal");
    }else{
        printf("Names are not equal");
    }
  
    return 0;
}

syntax of strcmp function: strcmp(String1, String2)
strcmp compares two strings character by character. This continues until the characters of two strings are different or a null character(\n) is reached. strcmp function is defined in string.h header file. Thats why you need to use the standard header: #include<string.h>

strcmp function returns :
0 : If the 2 strings are equal.
Positive integer : If the ASCII value of the first unmatched character(of String1) is greater than the second(String2)
Negative : If the ASCII value of the first unmatched character(of String1) is less than the second(String2)

2: Declare 2 dimensional array of string
To store array of strings, we need to use 2-dimensional array.
char names[][100] = {“Mahesh”, “Suresh”, “Sagar”};
100 denotes the maximum number of characters in a single string(including null character: \0)
You can declare array in this way too.
char names[3][100] = {“Mahesh”, “Suresh”, “Sagar”};
3 denotes the number of strings. 100 is the maximum number of characters in the string.
names[0] will have the string : Mahesh
names[1] will have: Suresh, names[2] will have Sagar
Since index of an array starts from zero.

#include <stdio.h>
#include <string.h>

int main()
{
    
  char names[][100] = {"Mahesh", "Suresh", "Sagar"};
  printf("\n %s",names[0]);
  printf("\n %s",names[1]);
  printf("\n %s",names[2]);

  return 0;
}

Iterate the array using for loop
Using the for loop, we can iterate the array. Use below code
for(int i=0;i<3; i++){
printf(“%s”,names[i]);
}

3: Search a String in an array.
We will use above concepts to create a program to search a string in an array.

#include <stdio.h>
#include <string.h>

int main()
{
    
  char names[][100] = {"Mahesh", "Suresh", "Sagar"};
  char friendName[] = "Suresh";   
   
  for(int i=0;i<3; i++){
	if(strcmp(names[i],friendName)==0){
		printf("Friend name is present in the array");	
	}
  }
  return 0;

}

I did these steps in the above program
Line 7: Created an array of strings
Line 8:Created a String
Line 10: Iterating the array
Line 11: Comparing array value with value of friendName String

Will try to cover complex scenario too. Will take input from user.
1: Get ‘N’ Number of Strings to enter : Example: If the user enters 5, then user wants to have 5 Strings in an array.
2: Create an array of Size N (Since we need to store N number of strings in an array)
3: Take N number of strings from user. Save it in an array
4: Get a word from user to search in this array
5: Iterate the array to search for a word that user has given.
6: If the word is present in the array, display message in console.
7: Exit

#include <stdio.h>
#include <string.h>
 
int main()
{
     
  int N;    
  printf("Enter a number\n");
  scanf("%d", &N);
   
  char names[N][100];
   
  printf("Enter %d words. Press Enter after each word\n", N);
  for(int i=0;i<N;i++){
      scanf("%s",names[i]);
  }
   
  char strToSearch[100];
  printf("Enter a word to search in an array\n");
  scanf("%s", strToSearch);
   
  printf("=======================\n");
  for(int i=0;i<N; i++){
    if(strcmp(names[i],strToSearch)==0){
        printf("String is present in the array");   
    }
  }
  return 0;
 
}

Here one issue is there while getting the string from user. What if user enters a string with space in between?. Example : If the user enters a string: Hello World Then scanf(“%s”, names[i]) will accept string only until it finds first space. Try below example.

#include <stdio.h>
#include <string.h>

int main()
{
    
   char name[20];
    scanf("%s",name);
    printf("Hello %s welcome",name);

  return 0;

}


To overcome this problem, instead of using scanf, use fgets function. Syntax is
char *fgets(char *str, int size, FILE *stream)
str : Points to an array of chars where the string read is copied.
size: Maximum number of characters to be copied into str
*stream: Pointer to a FILE object that identifies an input stream. stdin can be used as argument to read from the standard input.

#include <stdio.h>
#include <string.h>

int main()
{
    
   char name[20];
    fgets(name,20,stdin);
    printf("Hello %s welcome",name);

  return 0;

}



Leave a Reply

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