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
Ad

More Related Content

What's hot (20)

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
sandhya yadav
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
baabtra.com - No. 1 supplier of quality freshers
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
structure and union
structure and unionstructure and union
structure and union
student
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Strings
StringsStrings
Strings
Mitali Chugh
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
Poojith Chowdhary
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Data Types and Variables In C Programming
Data Types and Variables In C ProgrammingData Types and Variables In C Programming
Data Types and Variables In C Programming
Kamal Acharya
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
tanmaymodi4
 

Similar to Strings in c++ (20)

Chapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdfChapter 3 - Characters and Strings - Student.pdf
Chapter 3 - Characters and Strings - Student.pdf
mylinhbangus
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
Appili Vamsi Krishna
 
14 strings
14 strings14 strings
14 strings
Rohit Shrivastava
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
Sowmya Jyothi
 
Ch09
Ch09Ch09
Ch09
Arriz San Juan
 
String notes
String notesString notes
String notes
Prasadu Peddi
 
Strings
StringsStrings
Strings
Imad Ali
 
Chapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdfChapter 4 (Part II) - Array and Strings.pdf
Chapter 4 (Part II) - Array and Strings.pdf
KirubelWondwoson1
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
Hemantha Kulathilake
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
Md. Ashikur Rahman
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
International Islamic University
 
2 BytesC++ course_2014_c8_ strings
2 BytesC++ course_2014_c8_ strings 2 BytesC++ course_2014_c8_ strings
2 BytesC++ course_2014_c8_ strings
kinan keshkeh
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
JStalinAsstProfessor
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
AnkurRajSingh2
 
Unit 2
Unit 2Unit 2
Unit 2
TPLatchoumi
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
Strings in c
Strings in cStrings in c
Strings in c
vampugani
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
ssusere19c741
 
Ad

More from Neeru Mittal (19)

Using the Word Wheel to Learn basic English Vocabulary
Using the Word Wheel to Learn basic English VocabularyUsing the Word Wheel to Learn basic English Vocabulary
Using the Word Wheel to Learn basic English Vocabulary
Neeru Mittal
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
Neeru Mittal
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
Neeru Mittal
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
Neeru Mittal
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
Neeru Mittal
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
Neeru Mittal
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
Neeru Mittal
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
Neeru Mittal
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
Neeru Mittal
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
Arrays
ArraysArrays
Arrays
Neeru Mittal
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 
Using the Word Wheel to Learn basic English Vocabulary
Using the Word Wheel to Learn basic English VocabularyUsing the Word Wheel to Learn basic English Vocabulary
Using the Word Wheel to Learn basic English Vocabulary
Neeru Mittal
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
Neeru Mittal
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
Neeru Mittal
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
Neeru Mittal
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
Neeru Mittal
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
Neeru Mittal
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
Neeru Mittal
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
Neeru Mittal
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
Neeru Mittal
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
Neeru Mittal
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 
Ad

Recently uploaded (20)

New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 

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