SlideShare una empresa de Scribd logo
1 de 31
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Algorithmic Notations
Algorithmic NotationsAlgorithmic Notations
Algorithmic Notations
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
2D Array
2D Array 2D Array
2D Array
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Array data structure
Array data structureArray data structure
Array data structure
 
Strings
StringsStrings
Strings
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Circular queue
Circular queueCircular queue
Circular queue
 
Break and continue
Break and continueBreak and continue
Break and continue
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Type casting in c programming
Type casting in c programmingType casting in c programming
Type casting in c programming
 
Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)Computer Science-Data Structures :Abstract DataType (ADT)
Computer Science-Data Structures :Abstract DataType (ADT)
 

Similar a Strings in c++

Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiSowmya Jyothi
 
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.pdfKirubelWondwoson1
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01Md. 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.pdfSowmyaJyothi3
 
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.pptxJStalinAsstProfessor
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdfssusere19c741
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++Azeemaj101
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 

Similar a Strings in c++ (20)

Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
14 strings
14 strings14 strings
14 strings
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
Ch09
Ch09Ch09
Ch09
 
String notes
String notesString notes
String notes
 
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
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
 
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
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
2 BytesC++ course_2014_c8_ strings
2 BytesC++ course_2014_c8_ strings 2 BytesC++ course_2014_c8_ strings
2 BytesC++ course_2014_c8_ strings
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
Unit 2
Unit 2Unit 2
Unit 2
 
[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++
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Strings in c
Strings in cStrings in c
Strings in c
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 

Más de 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.pptxNeeru Mittal
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in PythonNeeru Mittal
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python PandasNeeru Mittal
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and TricksNeeru Mittal
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV ConnectivityNeeru Mittal
 
Working of while loop
Working of while loopWorking of while loop
Working of while loopNeeru 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
 
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 workingNeeru 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
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programmingNeeru 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
 

Más de Neeru Mittal (16)

Machine Learning
Machine LearningMachine Learning
Machine Learning
 
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
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Arrays
ArraysArrays
Arrays
 
Nested loops
Nested loopsNested loops
Nested loops
 
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
 
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++
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
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++
 

Último

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Último (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

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