SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot (20)

String in c programming
String in c programmingString in c programming
String in c programming
 
Inline function
Inline functionInline function
Inline function
 
C functions
C functionsC functions
C functions
 
Strings in C
Strings in CStrings in C
Strings in C
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Strings
StringsStrings
Strings
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Function in C
Function in CFunction in C
Function in C
 
Break and continue
Break and continueBreak and continue
Break and continue
 
File in C language
File in C languageFile in C language
File in C language
 
Strings
StringsStrings
Strings
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
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++
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 

Similar to 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 to 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
 

More from 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
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arraysNeeru 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
 
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 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
 

More from Neeru Mittal (17)

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++
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
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
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions 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++
 

Recently uploaded

When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 

Recently uploaded (20)

When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 

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