Array of string

Using an array of string, we can manipulate a group of strings easily.


Syntax

char name[number of strings][Maximum string length];

Example

char str[10][100];

where

str - the name of the string array

10  - total number of strings

100 - maximum string length




Initializing array of strings

Example

/*
 *total 5 strings
 *each string can at max 20 char long.
 */
char subject[5][20]={"Tamil","English","Maths","Science","Social Science"};

Pictorial Explanation

array of string





Printing the array of string

Example

#include<stdio.h>

int main()
{
    /*
     *total 5 strings
     *each string can at max 20 char long.
     */
     
    char subject[5][20]={"Tamil","English","Maths","Science","Social Science"};
    int i;
    
    //printing each string
    for(i = 0; i < 5; i++)
          printf("%s\n",subject[i]);
                
    return 0;
}




Getting the array of string from the user

Getting array of string input from the user and print it.

Example

#include<stdio.h>

#define size 5
#define length 20

int main()
{    
    char subject[size][length];
    int i;
    
    //getting input from user
    for(i = 0; i < size; i++)
          scanf("%s",subject[i]);
          
    //printing each string
    for(i = 0; i < size; i++)
          printf("%s\n",subject[i]);
                
    return 0;
}


Topics You Might Like