Home »
C programs »
C string programs
C program to read n strings and print each string's length
In this article, we will read n strings from the input and store it in array and print the length of each string in the array.
Submitted by Abhishek Pathak, on October 24, 2017
Problem statement
In this article, we will create a C program that will be based on Strings. We will read "n" number of strings, which will be specified by the user and store it in 2D array. Then we will print each string with their length side by side. This is an interesting program that deals with the Array of strings and how to perform string operations such as strlen() string length on them.
Following is the code for the same,
Read N strings and print them with the length program in C language
#include <stdio.h>
#include <string.h>
int main() {
// Declare Variables
char string[10][30]; // 2D array for storing strings
int i, n;
// Get the maximum number of strings
printf("Enter number of strings to input\n");
scanf("%d", &n);
// Read the string from user
printf("Enter Strings one by one: \n");
for (i = 0; i < n; i++) {
scanf("%s", string[i]);
}
// Print the length of each string
printf("The length of each string: \n");
for (i = 0; i < n; i++) {
// Print the string at current index
printf("%s ", string[i]);
// Print the length using `strlen` function
printf("%d\n", strlen(string[i]));
}
// Return to the system
return 0;
}
Output
Enter number of strings to input
3
Enter Strings one by one:
www.google.com
www.includehelp.com
www.duggu.org
The length of each string:
www.google.com 14
www.includehelp.com 19
www.duggu.org 13
Explanation
Let's break it down. Inside the main function, we have string array of characters. It is a 2D array that can store 10 strings with maximum 30 characters in each. Next we declare variables for loop and maximum user input strings.
After taking the value of n from user, we get input for each string one by one and using scanf() we store the characters in the array. In the second loop, for displaying the strings, we first print the string using printf() function. Notice that we have applied %s to specify to print characters of the string. Then, we print the length of corresponding string using strlen() function. Note that strlen() function returns an integer that is the length of the string. This is why we have specified %d specifier in printf function.
Finally, we return back to the system using return statement.
Hope you like the article, please share your thoughts.
C String Programs »