2. Contents
• What are Strings ?
• Strings in C++ (1 Dimensional Character arrays)
• Declaring String
• Initializing String
• Accessing characters of String
• Input a string using cin, gets() and getline()
• Displaying a String
• Array of strings(2 Dimensional character arrays)
• Initializing array of strings
• Input and displaying array of strings
• Sample Programs
3. What is a String?
A string is a collection of
characters . It is usually a
meaningful sequence
representing the name of an
entity.
Generally it is combination of
two or more characters
enclosed in double quotes.
“Good Morning” // string with 2 words
“Mehak” // string with one word
”B.P.” // string with letters and symbols
“” // an empty string
The above examples are also known as string
literals
4. How to store and process strings in c++?
• C++ does not provide with a special data type to store
strings.
• Thus we use arrays of the type char to store strings
• Strings in c++ are always terminated using a null character
represented by ‘0’
• Thus strings are basically one dimensional character arrays terminated
by a null character (‘0’)
• String literals are the values stored in the character array
5. Character arrays : declaration
To declare a character array or string the syntax is :
char arrayname[size];
Example :
char name[20];
Here name is a character array or string capable of storing maximum of 19
characters. One character is reserved for storing ‘0’
Thus the number of elements that can be stored in a string is always n-1, if the
size of the array specified is n. This is because 1 byte is reserved for the NULL
character '0' i.e. backslash zero.
6. Examples of array declarations
Array declaration Used to store
char city[20]; name of a city
char address[40]; address of a person
char designation[15]; designation
char author[25]; name of author
7. Character arrays : Initialization
char name[20]=“Jane Eyre”;
string
null character
. . . . . . . . . . . . . . . . . . . . .
The above string will have 9 characters and 1 space for the null. Thus size of
name will be 10.
J a n e E y r e ‘0’
name[0] name[1] name[7] name[9]
8. We can also initialize a character array in this way:
char name[ ]=“Jane Eyre”;
• In this case the array is initialized to the mentioned string and
the size of the array is the number of characters in the string
literal. Here it is 10.
• In the above declarations the null character is automatically
inserted at the end of the string.
Character arrays : Initialization
9. We can also initialize a string in this way:
char name[ ]={‘J’, ‘a’, ‘n’, ‘e’, ‘ ‘,’E’, ‘y’, ‘r’, ‘e’,’0’};
Note :
• Here the character array or string is initialized character by
character.
• The ‘0’ has to be inserted at the end. This is because in this method
the null character has to be inserted by the programmer.
Character arrays : Initialization
10. Some more examples of string initialization
Initialization Memory representation
char animal[]=“Lion”;
char location[]=“New Delhi”;
char serial_no[]=“A011”;
char company[]=“Airtel”;
L i o n ‘0’
N e w D e l h i ‘0’
A 0 1 1 ‘0’
A i r t e l ‘0’
11. String Input and Output
• We can input a string or character array in two ways:
1. Using cin>>
2. Using functions i. gets() ii. getline()
We shall study each of these one by one.
• A string is displayed using a simple cout<< statement
• Note that we do not need to use a loop to input or display a string. This is
because every string has a delimiter ie the ‘0’ character
12. Using cin>>
• The cin >> statement inputs a string without spaces. This is because the >>
operator stops input as soon as it encounters a space.
#include<iostream.h>
void main()
{ char city[13];
cout<<“n Enter name of the city”;
cin>>city;
cout<<“n you entered :”;
cout<<city;
}
Enter name of the city
Kuala Lumpur
you entered :Kuala
In the above code cin stops input as soon as it encounters a
space after Kuala. So the string variable city will contain
only Kuala. Note: ‘0’will be inserted after Kuala
u a l a 0
Explanation
Output
Contents of array
Program
13. Using gets()
#include<iostream.h>
void main()
{ char city[13];
cout<<“n Enter name of the city”;
gets(city);
cout<<“n you entered :”;
cout<<city;
}
Enter name of the city
Kuala Lumpur
you entered :Kuala Lumpur
In the above code, gets() will input the
entire string.
u a l a L u m p u r 0
Explanation
Output
Contents of array
Program
• The gets() function can be used to input a single line of text. Unlike cin it can input
a string with spaces. As soon as the enter is pressed the gets() function stops input
and the string is terminated.It belongs to the stdio.h header file.
14. Using getline()
• The getline() function can be used to input multiple lines of text.
The syntax is :
cin.getline(string, MAX, Delimiter character)
where
String is the character array . This is the variable in which the input is done
Max is the maximum number of characters allowed. This means that the value
determines the maximum number of characters that can be input
Delimeter character is the character which when encountered in the input stream
stops the input.The default delimeter charcter is ’n’
The getline function continues to input the string untill either the maximum
number of characters are input or it encounters the delimeter character
whichever comes first.
15. Using getline()
#include<iostream.h>
void main()
{ char para[80];
cout<<“n Enter in your own words:”;
cin.getline(para,80, ‘#’);
cout<<“n you entered :”;
cout<<para;
}
Enter in your own words : Pollution is a great factor
in determining the health
of today’s youth#
you entered : Pollution is a great factor
in determining the health
of today’s youth
In the above code, cin.getline() continues to input the
sting till it encountered a ‘#’. This is because here
‘#’is the delimeter character.
Explanation
Output
Program
The getline function inputs the string untill either the maximum number of
characters are input or it encounters the delimeter character whichever comes
first.
16. Using getline()
#include<iostream.h>
void main()
{ char para[80];
cout<<“n Enter in your own words:”;
cin.getline(para,60, ‘#’);
cout<<“n you entered :”;
cout<<para;
}
Enter in your own words : Pollution is a great factor
in determining the health
of today’s youth#
you entered : Pollution is a great factor
in determining the health
of toda
In the above code, since the maximum specified length is
60, so the string para will contain inpiut till toda. Note
that last space will be occupied by the ‘0’ character.
Explanation
Output
Program
The getline function inputs the string untill either the maximum number of
characters are input or it encounters the delimeter character whichever comes
first.
17. Some examples of cin.getline()
Statement. Character
array
Max
Characters
Delimeter
Character
Input
cin.getline(str1, 40); str1 40 n Will input a string with maximum 39
characters or until a n is encountered. It
will not input multiple lines of text
cin.getline(name, 20, ‘#’); name 20 # Will input a string with maximum 19
characters or until a ‘#’is encountered. It
will be able to input multiple line of text
cin.getline(text, 15, ‘@’); Text 15 @ Will input a string with maximum 14
characters or until a ‘@’is encountered. It
will be able to input multiple line of text
cin.getline(word, 25, ‘4’); word 25 4 Will input a string with maximum 24
characters or until a ‘4’is encountered. It
will be able to input multiple line of text
18. Program 1. Find the length of a string
#include<iostream.h>
#include<stdio.h>
void main( )
{
char word[80];
cout<<"Enter a string: ";
gets(word);
for(int i=0; word[i]!='0';i++); //Loop to find length
cout<<"The length of the string is : "<<i<<endl ;
Enter a string: Grand Canyon
The length of the string is : 12
19. Program 2. Program to count total number of
vowels and consonants present in a string
#include<iostream.h>
#include<stdio.h>
void main( )
{ char string[80]; int count1,count2; count1=count2=0;
cout<<"Enter a string: ";
gets(string);
for(int i = 0 ; string[i] != '0' ; i++)
{ if( string[i] = = 'a' || string[i] = = 'e' || string[i] = = ‘i' || string[i]
= = ‘o' || string[i] = = ‘u’ ||string[i] = = 'A' || string[i] = = 'E' ||
string[i] = = ‘I' || string[i] = = ‘O' || string[i] == ‘U' )
{count1++;}
else count2++; }
}
cout<<”The number of vowels is : ”<<count<<endl;
cout<<”The number of consonants is : ”<<count<<endl;
}
Enter a string: Grand theatre
The number of vowels is : 4
The number of vowels is : 8
20. Copying and comparing strings
• In c++ strings cannot be copied or compared using the simple
assignment or comparison operator.
• For eg:
char str1[20],str[2];
gets(str1);
str2=str1; // Not allowed
;
if(str1==str2) //Not allowed
{ …..
We need to perform the
comparison or assignment
using a loop or special
functions (covered later)
21. Copying one string to another
#include<iostream.h>
#include<stdio.h>
void main( )
{
char str1[20], str2[20];
cout<<"Enter first string: ";
gets(str1);
for(int i=0; str1[i]!='0';i++)
str2[i]=str1[i];
str2[i]=‘0’; // to terminate str2 manually
cout<<“nCopied String : “<<str2;
}
Enter first string: Poland
Copied String : Poland
22. Comparing two strings
#include<iostream.h>
#include<stdio.h>
void main( )
{
char str1[20], str2[20];
int flag=0;
cout<<"Enter first string: ";
gets(str1);
cout<<"Enter second string: ";
gets(str2);
for(int i=0; str[i]!='0';i++)
if(str1[i] !=str2[i])
{flag++; break;}
Enter first string: Poland
Enter second string: London
strings are not equal
if (flag==0)
cout<<“n strings are equal”;
else
cout<<“n strings are not equal”;
}
Enter first string: Information
Enter second string: Information
strings are equal
23. Two Dimensional Character Arrays
A two dimensional character array is basically an array of strings.
It can be represented as:
char stud_list[15][20];
We have two index values here; 15 and 20.
15 is the number of rows which represents the number of strings. 20 is the
number of columns which represents the size of each string.
Here stud_list contains the names of 15 students of a class where each
name can be upto 19 characters long.
24. Two dimensional character arrays
The general form will be
data-type array-name [m][n];
where m: no of strings
and n: size of each string
Examples:
Array declaration To store
1. char cities[20][25]; // names of 20 cities
2. char words[4][7]; // 4 words of maximum length 6 each
25. Initializing 2 D Strings
• We can initialize a 2 D string as follows:
char word[4][5]={“Cat”, “Boat”, “Mat”,”Rate”};
C a t ‘0’
B o a t ‘0’
M a t ‘0’
R a t e ‘0’
0 1 2 3 4
0
1
2
3
word[0][1]=a
word[3][0]=R
word[0]
word[3]
word[1]
word[2]
Memory
Representation
columns
rows
26. Accessing 2 D Strings: Example 1
C a t ‘0’
B o a t ‘0’
M a t ‘0’
R a t e ‘0’
0 1 2 3 4
0
1
2
3
char word[4][5]={“Cat”, “Boat”, “Mat”,”Rate”};
Statement output
cout<<word[2][0]; M
cout<<word[1][1]; o
cout<<word[2]; Mat
cout<<word[0]; Cat
28. Example 2
Statement output
cout<<word[0]; Mr. Bean
cout<<word[2][5]; e
cout<<word[4]; Arnold
cout<<word[5][2]; d
cout<<word[1][8];
char Name[6][10] = {"Mr. Bean", "Mr.Bush", "Nicole", "Kidman", "Arnold", "Jodie"};
29. Input and displaying array of strings
• To input an array of strings, we need to use loops:
char names[4][20]; // array capable of storing 4 strings
for(int i=0;i<4;i++) // loop to input a string one by one
gets(names[i]); // inputs string with index value i; i varying from 0 to 3
• To display an array of strings, we again need to use loops:
for(int i=0;i<20;i++) // loop to display a string one by one
cout(names[i]); // displays string with index value i; i varying from 0 to 3
30. Program to input and display the names of n
cities.
#include<iostream.h>
void main()
{ char city[20][25];
int n;
cout<<“n How many names do you wish to
input”;
cin>>n;
for(int i=0;i<n;i++)
{cout<<“n City “<<i+1<<“: ”;
gets(city[i]); }
cout<<“n displaying names of cities”;
for (i=0; i<n;i++)
cout<<“n”<<city[i];
How many names do you wish to input :
4
City 1 : Delhi
City 2 : Mumbai
City 3 : Chennai
City 4 : Kolkatta
cout<<“n displaying names of cities”;
Delhi
Mumbai
Chennai
Kolkatta
31. Program to display the words which start
with a capital ‘A’
#include<iostream.h>
void main()
{ char word[20][25];
int n;
cout<<“n No of word you wish to input”;
cin>>n;
for(int i=0;i<n;i++)
{cout<<“n “<<i+1<<“: ”;
gets(word[i]); }
cout<<“n Displaying words starting with ‘A’;
for (i=0; i<n;i++)
if(word[i][0]==‘A’) //checking first letter of each word
cout<<“n”<<word[i];
No of words you wish to input
4
1 : Summer
2 : Anomaly
3 : Potpourri
4 : Antelope
Displaying words starting with ‘A’
Anomaly
Antelope