C Program to find a string in an array of strings

Write a C program to find a string in an array of strings. The program should take input from the user.

Example,

Input
Number of Strings: 5
Ravil
James
Jeffree
Shane
PewDiePie

String to Search: PewDiePie

Output
PewDiePie is present at the 4th row

We will use a 2D character array to store the strings. Each row of the 2D will store one string. The program is very simple. We loop through each row of the 2D array and compare each string of the array with the string that we want to search. We will use strcmp() to compare the two strings.

Syntax for strcmp()

int strcmp(const char *str1, const char *str2);

strcmp() compares string str1 to string str2. The function returns 0 if both the strings are same.

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

int main() {

	char str[100];	// string to search
	char s[100][100];	// array of string
	int n;	// number of string in the array
	int i;

	printf("Enter Number of Strings: ");
	scanf("%d", &n);

	for (i = 0; i < n; ++i) {
		scanf("%s", s[i]);
	}

	printf("Enter string to search: ");
	scanf("%s", str);

	for (i = 0; i < n; ++i) {
		if (!strcmp(str, s[i])) {
			break;
		}
	}

	if (i != n) {
		printf("%s is present in the array at row %d", str, i);
	}
	else {
		printf("%s is not present in the array", str);
	}

}

Output

Enter Number of Strings: 5
James
Shane
Ravil
Smith
Nadi
Enter string to search: Ravil
Ravil is present in the array at row 2

Read

Leave a Comment

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