You are on page 1of 13

12

Arrays-II
(Non-numeric arrays)

In this chapter, you will learn:

 What is a string?
 One-dimensional array of characters
 String-handling functions
 Two-dimensional array of characters
What is a string?
Variables of type char can hold only a single character, so they have limited usefulness. We
also need a way to store strings, which are sequences of characters. A person's name and
address are examples of strings. Although there is no special data type for strings, C handles
this type of information with arrays of characters.
“A string is an array of characters terminated by a NULL character”
e.g., “I Love India” is a string. Whenever a string is stored in memory, the compiler
automatically inserts a NULL character (\0) at the end of string. This NULL character is a string
terminator, i.e., it denotes the end of string. This NULL character is the first ASCII character
which has a value of zero.

One-dimensional array of characters


Declaration:
The string that can hold an array of characters can be declared with the following syntax:
<Storage_class> char <array_name>[size];
where <Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array.
<array_name> is any valid identifier.
Size, a positive integer, determines the number of characters in the string.
Ex: char name[20]; //can hold a string of 19 characters; one location is for NULL
char a [35]; //can hold a string of 34 characters; one location is for NULL
When we declare a character array, an additional element is allocated for the NULL character.
Initialization:
This one-dimensional array of characters can be initialized by using assignment operator as
follows:
char a[13]={‘I’,’ ‘,’L’,’o’,’v’,’e’,’ ‘,’I’,’n’,’d’,’I’,’a’};
is equivalent to
char a[13]=”I Love India”;
In both of the cases, the NULL character can be appended to the string automatically. If the
length of the string is exceeded than the specified size in square brackets, then the compiler
gives the error. This error can be rectified with the help of the following initialization statement
that automatically allocates memory based on the number of characters in that string:
char a[]={‘I’,’ ‘,’L’,’o’,’v’,’e’,’ ‘,’I’,’n’,’d’,’I’,’a’};
(or)
char a[]=”I Love India”;
When the character array is initialized, the memory map for that array is as follows:

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012

I L o v e I n d i a \0

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a[10] a[11] a[12]
2
Reading and Printing:
There are 3 ways to read a string using keyboard:
 By using scanf() function
 By using gets() function
 By using getchar() repeatedly (with the help of loops)
There are 3 ways to print a string onto the monitor:
 By using printf() function
 By using puts() function
 By using putchar() repeatedly (with the help of loops)

By using the scanf() and printf() functions: The scanf() function with the conversion
character %s can be used to read a string using keyboard. The printf() function with the same
conversion character can be used to print a string onto monitor. E.g.,
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
scanf(“%s”,str);
printf(“\n Your Name=%s”,str);

}
Usually, scanf() statement expects an address of the variable. Because the name of the array
itself is an address of it, we don’t use an ampersand (&) before the name of the string. The %s
option uses a blank space as a delimiter and hence it considers the character separated by
blank space as two strings.
The disadvantage of scanf() function is that there is no way to read a multi-word string
(i.e., string with spaces) into a single variable. The scanf() function terminates the input string
when it finds blank space in input string. E.g., if the input for scanf() function is “pradeep
kumar”, the string variable str holds only the string pradeep.
To read a multi-word, we can use the following form of scanf():
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
scanf(“[^\n]”,str);//[^\n] means read set of characters except new line character
printf(“\n Your Name=%s”,str);

By using the gets() and puts() functions: The gets() function can also be used to read a
string using keyboard. It reads and assigns the input string to the character array until the
ENTER key is pressed. The input string can consist of blank spaces and tabs as part of it. The
puts() function is used to print that string which was read by using gets() or scanf().

3
Ex:
#include<stdio.h>
main()
{
char str[25];
printf(“\n Enter your name:”);
gets(str);
puts(str);

}
The string can be entered until the ENTER key is pressed and can be stored in string variable.
Now, suppose that we input the string “pradeep kumar”. Then the variable str holds the whole
string “pradeep kumar”.
The disadvantage of gets() function is that it can be used to read only one string at a
time. E.g., the following gets() statement is invalid:
gets(str1,str2); //invalid
The gets() function expects only one string as an argument. If more than one string is input to
this function, the compiler gives an error “too many arguments to function gets”

However, a scanf() function can be used to read more than one string at a time.
E.g., scanf(“%s%s%s”,str1,str2,str3); can be used to read 3 strings.

By using a loop: A string can be read character by character by using a for loop (or any
loop). Each time the loop runs, the getchar() function takes the character from the keyboard
and that character will be assigned to the one of character array’s locations. The loop should
be stopped when the new line character is encountered. When the repetition has stopped, the
last location should occupy the NULL character for denoting the end of string.
For printing the string using a loop, the iterative process should start at 0 th location and
should terminate before the NULL character. In each iteration, the character should be printed
with the help of putchar() or printf() with %c conversion specifier.
E.g.,
#include<stdio.h>
main()
{
char str1[23],ch;
int i;
printf("\n Enter any string:");
for(i=0;(ch=getchar())!='\n';i++)
str1[i]=ch;
str1[i]='\0';
for(i=0;str1[i]!=’\0’;i++)
putchar(str1[i]);
}

4
Examples:

/* Program to find the length of the /*Program to copy one string to


string*/ another string*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
char str[20]; char str1[20],str2[20];
int count,i; int i;
puts(“\nEnter any string”); printf(“\n Enter any string:”);
gets(str); gets(str1);
count=0; printf(“\n Original string=%s”,str1);
for(i=0;str[i]!=’\0’;i++) for(i=0;str1[i]!=’\0’;i++)
count++; str2[i]=str1[i];
printf(“\n The length of string=%d”,count); str2[i]=’\0’;
} printf(“\n Copied string=%s”,str2);
}

/*Method1: Program to reverse a /*Method2: Program to reverse a


string*/ string*/
#include<stdio.h> #include<stdio.h>
main() main()
{ {
char str[20]; char str[20],temp;
int count,i; int count,i,j;
puts(“\nEnter any string”); puts(“\nEnter any string”);
gets(str); gets(str);
count=0; count=0;
for(i=0;str[i]!=’\0’;i++) for(i=0;str[i]!=’\0’;i++)
count++; count++;
for(i=count-1;i>=0;i--) for(i=0,j=count-2;i<=j;i++,j--)
printf(“%c”,str[i]); {
} temp=str[i];
str[i]=str[j];
str[j]=temp;
}
printf(“\nReversed string=%s”,str);
}
/*Program to count no.of vowels and /*Program to convert the case of text*/
consonants in a line of text*/ #include<stdio.h>
#include<stdio.h> main()
main() {
{ char text[50];
char text[50]; printf(“\n Enter a line of text:”);
int nv=0,nc=0; gets(text);
printf(“\n Enter a line of text:”); for(i=0;text[i]!=’\0’;i++)
gets(text); {
for(i=0;text[i]!=’\0’;i++) if(text[i]>=’A’ && text[i]<=’z’)
{ text[i]=text[i]+32;
if(text[i]==’a’||text[i]==’e’||text[i]==’o’|| else
text[i]==’i’||text[i]==’u’) text[i]=text[i]-32;
nv++; }
else printf(“\n converted text=%s”,text);
nc++; }
}
printf(“\n No.of vowels=%d”,nv);
printf(“\n No.of consonants=%d”,nc); }

5
/*Program to count no.of lines, words /* Program to compare two strings*/
and characters in multiple lines of text*/ #include<stdio.h>
#include<stdio.h> main()
main() {
{ char str1[20],str2[20];
char text[150],ch; int count1,count2;
int nl=0,nw=0,nc=0; puts(“\nEnter first string”);
printf(“\n Enter multiple lines of text (end with gets(str1);
#):”); puts(“\n Enter second string”);
for(i=0;(ch=getchar())!=’#’;i++) gets(str2);
{
nc++; count1=0;
if(ch==’ ‘) for(i=0;str1[i]!=’\0’;i++)
nw++; count1++;
else if(ch==’\n’)
nl++; count2=0;
else ; for(i=0;str2[i]!=’\0’;i++)
} count2++;
printf(“\n No.of lines=%d”,nl);
printf(“\n No.of words=%d”,nc); if(count1!=count2)
printf(“\n No.of characters=%d”,nc); printf(“\n Strings are not equal”);
} else
{
/* Program to concatenate two strings*/ for(i=0;i<count1;i++)
#include<stdio.h> {
main() if(str1[i]==str2[i])
{ {
char str1[40],str2[20]; c=0;
int count; break;
puts(“\nEnter first string”); }
gets(str1); else if(str1[i]>str2[i])
puts(“\n Enter second string”); {
gets(str2); c=1;
break;
count=0; }
for(i=0;str1[i]!=’\0’;i++) else
count++; {
c=-1;
for(i=0;str2[i]!=’\0’;i++) break;
str1[count++]=str2[i]; }
str1[count]=’\0’; }
if(c==0)
printf(“\n concatenated string=%s”,str1); printf(“\n Two strings are equal”);
} else if(c>0)
printf(“\n first string is greater”);
else
printf(“\n Second string is bigger”);
}
}

6
String handling functions
C supports a number of string handling functions. All of these built-in functions are
defined in the header file string.h. Therefore, whenever we use one of these string handling
functions, we should add the preprocessor statement #include<string.h> to our program.
Some of the string- handling functions are:
 strcmp()
 strcpy()
 strcat()
 strlen()
 strrev()
 strncmp()
 strncpy()
 strncat()
 strlwr()
 strupr()
 strchr()

strcmp() function: This function compares two strings character by character (ASCII
comparison) and returns one of three values {-1,0,1}. Its syntax is as follows:

strcmp(string1,string2);

where string1 and string2 are one-dimensional arrays of characters.


When this function is invoked with two strings as arguments, then:
 This function returns -1 or negative integer, if the ASCII value of the character of the
first string is less than that of second string;
 It returns 0 (zero), if both strings are equal;
 It returns 1 or a positive integer, if the ASCII value of the character of first string is
greater than that of the second string.

Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”ABC”;
char str2[]=”abc”;
int ans;
ans=strcmp(str1,str2);
printf(“\n Answer=%d”,ans);
}

Here ASCII value of A (i.e 65)is less than a(i.e 97).thus,the above statement returns -32(i.e
65-97) and is assigned to ans.

7
strcpy() function: This function is used to copy one string to the other. Its syntax is as
follows: strcpy(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function copies the content of string2 to string1. E.g., string1 contains master and
string2 contains madam, then string1 holds madam after execution of the strcpy() function.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”master”;
char str2[]=”madam”;
strcpy(str1,str2);
printf(“\n Copied string=%s”,str1);
}

strcat() function: This function is used to concatenate two strings. i.e., it appends one string
at the end of the specified string. Its syntax as follows:

strcat(string1,string2);

where string1 and string2 are one-dimensional character arrays.


This function joins two strings together. In other words, it adds the string2 to string1
and the string1 contains the final concatenated string. E.g., string1 contains prog and string2
contains ram, then string1 holds program after execution of the strcpy() function.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”prog”;
char str2[]=”ram”;
strcat(str1,str2);
printf(“\n Concatenated string=%s”,str1);
}
strlen() function: This function is used to find the length of the string excluding the NULL
character. In other words, this function is used to count the number of characters in a string.
Its syntax is as follows:
strlen(string1);

where string1 is the one-dimensional array of characters.


This function returns an integer value that is the count of characters in the string. E.g.,
string1 contains pradeep is a good boy then strlen() function returns the value 21.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”pradeep is a good boy”;
int length;
length=strlen(str1);
printf(“\n Length of string=%d”,length);
}

8
strrev() function: This function is used to find the reversed string of a given string. Its
syntax is as follows: strrev(string1);

where string1 is the one-dimensional array of characters.


This function stores the reversed string of string1 in that argument string1 only. E.g.,
string1 contains master then the same string1 contains retsam after execution of strrev() .
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”master”;
strrev(str1);
printf(“\n Reversed string=%s”,str1);
}

strncmp() function: This function compares the first n characters of two input strings and
returns one of these 3 values {-1,0,1} same as strcmp() function. Its syntax is as follows:

strncmp(string1,string2,n);

where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds master and string2 holds minister and n=4, then strncmp()
compares first 4 characters of both of these strings character by character and returns the
value (i.e., -1) as strcmp() returns.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”master”;
char str2[]=”minister”;
int value;
value=strncmp(str1,str2,4);
printf(“\n Returned value=%d”,value);
}

strncpy() function: This function compares the first n characters of second string to the first
string. Its syntax is as follows:

strncpy(string1,string2,n);

where string1 and string2 are the one-dimensional arrays of characters and n is an integer.

e.g., string1 holds Delhi and string2 holds Bangalore and n=4, then strncpy() copies
the first 4 characters of string2 to string1. The string1 holds the copied substring Bang.

9
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Delhi”;
char str2[]=”Bangalore”;
strncpy(str1,str2,4);
printf(“\n copied string=%s”,str1);
}

strncat() function: This function concatenates the first n characters of second string to the
first string. Its syntax is as follows:

strncat(string1,string2,n);

where string1 and string2 are the one-dimensional arrays of characters and n is an integer.
e.g., string1 holds Master and string2 holds System and n=3, then strncpy()
concatenates or adds the first 3 characters of string2 to string1. The string1 holds the
concatenated string MasterSys.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Master”;
char str2[]=”System”;
strncat(str1,str2,3);
printf(“\n concatenated string=%s”,str1);
}

strlwr() function: This function converts all the uppercase alphabets into lowercase. Its
syntax is as follows:

strlwr(string1);

where string1 is the one-dimensional arrays of characters.


e.g., string1 holds Master MINDS, then strlwr() converts all the uppercase alphabets of
string1 to lowercase. The string1 holds the lowercase string master minds.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Master MINDS”;
strlwr(str1); /* Alternative for this strlwr() is tolower(str1)*/
printf(“\n converted string=%s”,str1);
}

strupr() function: This function converts all the lowercase alphabets into uppercase. Its
syntax is as follows:

strupr(string1);

10
where string1 is the one-dimensional arrays of characters.
e.g., string1 holds Master MINDS, then strupr() converts all the lowercase alphabets of
string1 to uppercase. The string1 holds the upprecase string MASTER MINDS.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Master MINDS”;
strupr(str1); /* Alternative for this strlwr() is toupper(str1)*/
printf(“\n converted string=%s”,str1);
}

strchr() function: This function searches for a specified character in a given string. If that
string holds specified character, strchr() function returns first occurrence of character;
otherwise NULL. Its syntax is as follows:

strchr(string1,ch);

where string1 is the one-dimensional arrays of characters and ch is the character.


e.g., string1 holds Ramesh and character to be searched is m, then strchr() searches for
character a in the string and returns true.
Ex: #include<string.h>
#include<stdio.h>
main()
{
char str1[]=”Ramesh”;
int ans;
ans=strchr(str1,’m’);
printf(“\n Returned value=%d”,ans);
}

Other useful string functions from string.h

Function Purpose
strrchr(string,char) Returns the last occurrence of a specified character in the string.
strcmpi(string1,string2) Compares string2 to string1 with out considering case of text.
strncmpi(string1,string2,n) Compares at most n characters string2 to string1 ignoring case.
stpcpy(string1,string2) Same as strcpy() except it returns string2+strlen(string1).
strdup(string1) Returns the duplicate copy of string1.
strstr(string1,string2) Finds the first occurrence of substring string2 in string1.
strset(string1,char) Sets all the characters of string1 to a given character.
strnset(string1,char,n) Sets all the first n characters of string1 to a given character.

11
Two-dimensional array of characters
By using one-dimensional array, only one string (including spaces) is accepted and processed.
Some times, it is necessary for us to process group of strings. In such situations, we need a
two-dimensional array. A two-dimensional array of characters is an array of one-dimensional
arrays of characters. This means that, a two-dimensional character array consists of strings as
its individual elements.

Declaration: Like Two-dimensional numeric arrays, Two-dimensional character arrays should


be declared before it is used. A Two-dimensional array of characters can be declared as
follows:
<Storage_class> char <array_name>[row][column];
where <Storage_class> is any one of auto, extern, static or register, an optional one.
char is the data type that determines the type of elements in the array.
<array_name> is any valid identifier.
row, a positive integer, determines the number of strings in the array.
Column, a positive integer, determines the number of characters a string can hold.
Ex: char a[5][10]; //can hold 5 input strings, each input string should be of length 9 chars.

Initialization: Like One-dimensional character array, a Two-dimensional character array can


also be initialized with the help of assignment operator as follows:
char names[3][10]={ {‘R’,’a’,’j’,’ ’,’k’,’u’,’m’,’a’,’r’},
{‘S’,’a’,’n’,’j’,’a’,’n’,’a’},
{‘P’,’o’,’o’,’j’,’a’}};
is equivalent to
char names[3][10]={“Raj kumar”,”Sanjana”,”Pooja”};
When this Two-dimensional character array is initialized, it will be in memory as follows:

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

names[0] R a j k u m a r \0
names[1] S a n j a n a \0
names[2]
P o o j a \0

Reading and printing multiple strings: The above three methods will be very helpful in
reading and printing each string with the help of a loop. The loop is used for keeping track of
loop counter of rows of two-dimensional array. The following example clears this concept:

12
#inlcude<stdio.h>
main()
{
char names[10][15];
int n,i;
printf(“\n How many strings:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter %d string:”,i+1);
scanf(“%s”,names[i]);
}
printf(“\n Given strings are:”);
for(i=0;i<n;i++)
printf(“%s\t”,names[i]);
}

Examples:
/*A program to sort strings in /*A program to search for a string in
alphabetical order*/ multiple strings*/
#inlcude<stdio.h> #inlcude<stdio.h>
#include<string.h> #include<string.h>
void sort(char [][],int); int search(char [][],int,char[]);
main() main()
{ {
char names[10][15]; char names[10][15],ele[15];
int n,i; int n,i,pos;
printf(“\n How many strings:”); printf(“\n How many strings:”);
scanf(“%d”,&n); scanf(“%d”,&n);
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
printf(“\n Enter %d string:”,i+1); printf(“\n Enter %d string:”,i+1);
scanf(“%s”,names[i]); scanf(“%s”,names[i]);
} }
sort(names,n); printf(“\nEnter string to search);
} scanf(“%s”,ele);
void sort(char names[][],int n) pos=search(names,n,ele);
{ if(pos<=0)
int i,j; printf(“\n String is not found”);
char temp[15]; else
for(i=0;i<n;i++) printf(“\nString is found at %d position”,pos);
{ }
for(j=i+1;j<n;j++) void sort(char names[][],int n,char ele[])
{ {
if(strcmp(names[i],names[j])>0) int i,pos=-1;
{ for(i=0;i<n;i++)
strcpy(temp,names[i]); {
strcpy(names[i],names[j]); if(strcmp(names[i],ele)==0)
strcpy(names[j],temp); {
} pos=i+1;
} break;
} }
printf(“\n Strings in alphabetical order:”); }
for(i=0;i<n;i++) return pos;
printf(“%s\t”,names[i]); }
}

13

You might also like