Handling multiple string in C

 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: 
studyforfuture
Creatyour blog
lion is the king

The length of each string: 
studyforfuture 14
Creatyour blog 14
lion is the king 16
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.

No comments:

Post a Comment

Featured Post

Core and Advance Python

                      Language Fundamentals