Professional Documents
Culture Documents
Objectives
• Define what is strings
• Declare string
• Access the elements of an array using [], at(),
back(), front()
• Use input functions such as getline(), push_back()
• Use size manipulation function such as length(),
capacity(), resize()
Strings
string sampleString;
sampleString = “This is a sample String”;
• As an output
cout<<sampleString << endl;
• Or
cout<<“This is a sample String” << endl;
Declare Strings
#include <string>
using namespace std;
Accessing Elements of String
1. Using [ ] operator
• it give an access to the element / character at
a given index
• If index out of range, program might crash
Accessing Elements of String
Accessing Elements of String
1. getline()
• this functions is used to input whole lines or
sentences into a string
• input stream function “cin” it input strings but
it will only allow you to input one word
• getline functions reads till a new line is found
Input Functions
cin getline()
Input Functions
2. push_back()
• this functions it allows
to append characters
to the end of your
string.
Size Manipulation
1. length()
• It return the number
of bytes / characters
in a string
Size Manipulation
2. capacity()
• It returns the number
of bytes allocated in
memory for a string
Size Manipulation
3. resize()
• it allows to instantly
change the number
of characters in a
string
Functions for Iteration
• Iterator functions are used to point at the first or last
byte in a string
1. begin()
This function returns an iterator pointing to the
beginning of a string.
2. end()
This function returns an iterator pointing to the
end of a string.
Functions for Iteration
Functions for Iteration
• Iterator functions are used to point at the first or last
byte in a string
3. rbegin()
This function returns a reverse iterator pointing to
the end of a string
4. rend()
This function returns a reverse iterator pointing to
the end of a string
Functions for Iteration
Working with Multiple Strings
1. copy()
• it is used if you need to copy your string into a
character array
• it needs three arguments
- target char array
- number of bytes
- string start position
Working with Multiple Strings
2. swap()
• This function allows us to swap the contents of 2
strings without needing to use a third variable.
Working with Multiple Strings
Working with Multiple Strings
3. concatenate using append()
Concatenate the contents of 2 strings into 1 string using
append function.
Working with Multiple Strings
Working with Multiple Strings
4. concatenate using + operator
Concatenate the contents of 2 strings into 1 string by
adding them.
Working with Multiple Strings
Problem1
• create a program that will allow the user to input sentence, and it
will the asked the user to find a character in the sentence. Then it
will count that character and display the value.