SlideShare a Scribd company logo
Strings in C++
Character Arrays
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
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
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
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.
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
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]
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
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
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’
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
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
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.
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.
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.
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.
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
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
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
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)
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
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
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.
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
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
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
Initializing :Example 2
char Name[6][10] = {"Mr. Bean", "Mr.Bush", "Nicole", "Kidman", "Arnold", "Jodie"};
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"};
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
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
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

More Related Content

PPTX
C++ string
PPTX
Oop c++class(final).ppt
PPTX
Tokens in C++
PPTX
Constructors and destructors
PPTX
Introduction Of C++
PPT
Basics of c++
PPSX
C++ Programming Language
PPTX
Pointer in C++
C++ string
Oop c++class(final).ppt
Tokens in C++
Constructors and destructors
Introduction Of C++
Basics of c++
C++ Programming Language
Pointer in C++

What's hot (20)

PDF
Managing I/O in c++
PPTX
classes and objects in C++
PPT
Operator Overloading
PPTX
Function C programming
PPTX
Chapter 05 classes and objects
PPT
Strings
PPTX
Encapsulation C++
PPTX
Constructors in C++
PPTX
PPTX
INLINE FUNCTION IN C++
PPTX
Polymorphism In c++
PPTX
Passing an Array to a Function (ICT Programming)
PDF
Methods in Java
PPT
Function overloading(c++)
PPTX
Constructor and Types of Constructors
PPTX
Recursive Function
PPTX
Call by value
PPTX
Linked list
PDF
Arrays in Java
Managing I/O in c++
classes and objects in C++
Operator Overloading
Function C programming
Chapter 05 classes and objects
Strings
Encapsulation C++
Constructors in C++
INLINE FUNCTION IN C++
Polymorphism In c++
Passing an Array to a Function (ICT Programming)
Methods in Java
Function overloading(c++)
Constructor and Types of Constructors
Recursive Function
Call by value
Linked list
Arrays in Java
Ad

Similar to Strings in c++ (20)

PPT
Week7.ppt
PDF
String class and function for b.tech iii year students
PDF
C string _updated_Somesh_SSTC_ Bhilai_CG
PDF
Chapter 3 - Characters and Strings - Student.pdf
PPT
Strings
PPTX
Cs1123 9 strings
PPTX
Chapter 9 C++ Programming Absolute C++ Lecture Slides
PPT
sav_ch09.ppt
PDF
Chapter 4 (Part II) - Array and Strings.pdf
PPT
Strings
PPT
Strings
PPT
Strings
PPTX
Arrays & Strings.pptx
PDF
C Strings oops with c++ ppt or pdf can be done.pdf
PPTX
COm1407: Character & Strings
PPTX
lecture-5 string.pptx
PPTX
String Handling in c++
PPTX
Presentation more c_programmingcharacter_and_string_handling_
PPTX
String handling
Week7.ppt
String class and function for b.tech iii year students
C string _updated_Somesh_SSTC_ Bhilai_CG
Chapter 3 - Characters and Strings - Student.pdf
Strings
Cs1123 9 strings
Chapter 9 C++ Programming Absolute C++ Lecture Slides
sav_ch09.ppt
Chapter 4 (Part II) - Array and Strings.pdf
Strings
Strings
Strings
Arrays & Strings.pptx
C Strings oops with c++ ppt or pdf can be done.pdf
COm1407: Character & Strings
lecture-5 string.pptx
String Handling in c++
Presentation more c_programmingcharacter_and_string_handling_
String handling
Ad

More from Neeru Mittal (19)

PPTX
Using the Word Wheel to Learn basic English Vocabulary
PPTX
Machine Learning
PPTX
Introduction to AI and its domains.pptx
PPTX
Brain Storming techniques in Python
PPTX
Data Analysis with Python Pandas
PPTX
Python Tips and Tricks
PPTX
Python and CSV Connectivity
PPTX
Working of while loop
PPTX
Increment and Decrement operators in C++
PPTX
Library functions in c++
PPTX
Two dimensional arrays
PPTX
Arrays
PPTX
Nested loops
PPTX
Iterative control structures, looping, types of loops, loop working
PPTX
Variables in C++, data types in c++
PPTX
Operators and expressions in C++
PPTX
Introduction to programming
PPTX
Getting started in c++
PPTX
Introduction to Selection control structures in C++
Using the Word Wheel to Learn basic English Vocabulary
Machine Learning
Introduction to AI and its domains.pptx
Brain Storming techniques in Python
Data Analysis with Python Pandas
Python Tips and Tricks
Python and CSV Connectivity
Working of while loop
Increment and Decrement operators in C++
Library functions in c++
Two dimensional arrays
Arrays
Nested loops
Iterative control structures, looping, types of loops, loop working
Variables in C++, data types in c++
Operators and expressions in C++
Introduction to programming
Getting started in c++
Introduction to Selection control structures in C++

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Complications of Minimal Access Surgery at WLH
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
01-Introduction-to-Information-Management.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
master seminar digital applications in india
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Classroom Observation Tools for Teachers
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Complications of Minimal Access Surgery at WLH
Anesthesia in Laparoscopic Surgery in India
01-Introduction-to-Information-Management.pdf
Insiders guide to clinical Medicine.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
GDM (1) (1).pptx small presentation for students
Renaissance Architecture: A Journey from Faith to Humanism
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
master seminar digital applications in india
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Classroom Observation Tools for Teachers
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Pharma ospi slides which help in ospi learning
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

Strings in c++

  • 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
  • 27. Initializing :Example 2 char Name[6][10] = {"Mr. Bean", "Mr.Bush", "Nicole", "Kidman", "Arnold", "Jodie"};
  • 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