Module 4.1 - Strings
Module 4.1 - Strings
INTRODUCTION
A string is a null-terminated character array. This means that after the last character, a null
character (‘\0’) is stored to signify the end of the character array.
Declaration:
The general form of declaring a string is
char string_name[size];
E.g. char name[20], city[20];
Initializing:
E.g.1: char city[9] = “New York”;
E.g. 2: char city[9] = {‘N’,’e’,’w’,'',’Y’,’o’,’r’,’k’,’\0’};
Null character ‘\0’ inserted by compiler in e.g.1.
Specify array size considering ‘\0’ also.
E.g.: char city[9] = “New York”;
char str1[9] ;
str1 = “Good”; // Error: Not allowed to assignment like this in C
READING STRINGS
WRITING STRINGS
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15];
char str2[15] = "Hello World";
strcpy(str1,str2);
printf("Copied string:");
puts(str1);
}
3. strcat( ): Concatenates two strings.
Usage: strcat(str1,str2);
Str2 is appended at the end of str1. The combined string is stored in str1. Make sure str1 is large
enough to contain concatenation of str1 and str2.
// strcat
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15] = "Hello";
char str2[6] = "World";
strcat(str1,str2);
puts(str1);
}
o/p: HelloWorld
ARRAYS OF STRINGS
Now suppose that there are 20 students in a class and we need a string that stores names of all the
20 students. Here, we need a string of strings or an array of strings.
An array of string is declared as:
char names[20][30];
Where,
The first index represents the number of strings and the second index specifies the length of
individual string. So here, we allocate space for 20 names where each name can be maximum of 30
characters long.
General Syntax:
<data_type> <array_name> [row_size][column_size];
Let us see the memory representation of an array of strings. If we have an array declared as,
char name[5][10] = {“Ram”, “Mohan”, “Shyam”, “Hari”, “Gopal”};
WRITE A PROGRAM TO READ AND PRINT THE NAMES OF N STUDENTS OF A
CLASS
#include <stdio.h>
int main()
{
char names[5][10];
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Enter the name of %dth student : “, i+1);
gets(names[i]);
}
for(i=0;i<n;i++)
{
puts(names[i]);
}
return 0;
}