C++ Programming
Topperworld.in
String in C++
⚫ C++ has in its definition a way to represent a sequence of characters as an
object of the class. This class is called std:: string.
⚫ The string class stores the characters as a sequence of bytes with the
functionality of allowing access to the single-byte character.
The syntax to create a string in C++ is quite simple. We use the string keyword
to create a string in C++. However, we also need to include the standard string
class in our program before using this keyword.
Syntax:
string str_name = "This is a C++ string";
➔ Types of String Representation in C++
There are two ways in which we can save/ represent the strings in C++,
namely:
1. C- style string
2. String Class
C-Style Character String
A string is defined as an array of characters in the C programming
language that ends with the null or termination character (\0). Because
it indicates to the compiler where the string terminates, the termination
is crucial. C-style character strings are also supported in C++.
©Topperworld
C++ Programming
Syntax:
char str_array[7] = {‘D’, ‘e’, ‘e’, ‘p’, ‘a’, ‘k’, ‘\0’};
Alternatively, we can write the above string as follows:
char str_array[] = “Deepak”;
The char str_array[] will still include 6 characters due to the fact that C++
automatically adds a null character at the end of the string.
String Class
If the string or char array is not null-terminated, it can result in a wide
variety of potential issues, making C-style strings relatively hazardous. A
considerably safer option is the std::string class (i.e. the standard string
class) offered by the C++ Standard Library. However, the string class
stores the characters as a sequence in terms of bytes and hence allows
for single-byte character access.
Syntax:
std::string str("Topperworld");
❖ String vs Character Array
String Char Array
A string is a class that defines A character array is simply an array
objects that be represented as a of characters that can be
stream of characters. terminated by a null character.
In the case of strings, memory The size of the character array has
is allocated dynamically. More to be allocated statically, more
©Topperworld
C++ Programming
String Char Array
memory can be allocated at run time memory cannot be allocated at run
on demand. As no memory is time if required. Unused
preallocated, no memory is wasted. allocated memory is also wasted
As strings are represented as There is a threat of array decay in
objects, no array decay occurs. the case of the character array.
Strings are slower when compared
Implementation of character array
to implementation than character
is faster than std:: string.
array.
String class defines a number of Character arrays do not
functionalities that allow manifold offer many inbuilt functions to
operations on strings. manipulate strings.
❖ Operations on Strings
1) Input Functions
Function Definition
This function is used to store a stream of characters as
getline()
entered by the user in the object memory.
This function is used to input a character at the end of the
push_back()
string.
Introduced from C++11(for strings), this function is used to
pop_back()
delete the last character from the string.
©Topperworld
C++ Programming
Example:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a line of text: ";
std::getline(std::cin, input);
std::cout << "You entered: " << input <<
std::endl;
return 0;
}
Output:
Enter a line of text: Hello Topperworld!.
You entered: Hello Topperworld!.
2) Capacity Functions
Function Definition
This function returns the capacity allocated to the string,
capacity() which can be equal to or more than the size of the string.
Additional space is allocated so that when the new
©Topperworld
C++ Programming
Function Definition
characters are added to the string, the operations can be
done efficiently.
This function changes the size of the string, the size can be
resize()
increased or decreased.
length() This function finds the length of the string.
This function decreases the capacity of the string and
makes it equal to the minimum capacity of the string. This
shrink_to_fit()
operation is useful to save additional memory if we are
sure that no further addition of characters has to be made.
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
std::cout << "Initial capacity: " <<
numbers.capacity() << std::endl;
// Adding elements to the vector
for (int i = 0; i < 10; ++i) {
numbers.push_back(i);
std::cout << "Size: " << numbers.size() << ",
Capacity: " << numbers.capacity() << std::endl;
}
return 0;
}
©Topperworld
C++ Programming
Output:
Initial capacity: 0
Size: 1, Capacity: 1
Size: 2, Capacity: 2
Size: 3, Capacity: 4
Size: 4, Capacity: 4
Size: 5, Capacity: 8
Size: 6, Capacity: 8
Size: 7, Capacity: 8
Size: 8, Capacity: 8
Size: 9, Capacity: 16
Size: 10, Capacity: 16
3) Iterator Functions
Function Definition
begin() This function returns an iterator to the beginning of the string.
This function returns an iterator to the next to the end of the
end()
string.
This function returns a reverse iterator pointing at the end of the
rbegin()
string.
This function returns a reverse iterator pointing to the previous
rend()
of beginning of the string.
©Topperworld
C++ Programming
Function Definition
This function returns a constant iterator pointing to the
cbegin() beginning of the string, it cannot be used to modify the contents
it points-to.
This function returns a constant iterator pointing to the next of
cend() end of the string, it cannot be used to modify the contents it
points-to.
This function returns a constant reverse iterator pointing to the
crbegin() end of the string, it cannot be used to modify the contents it
points-to.
This function returns a constant reverse iterator pointing to the
crend() previous of beginning of the string, it cannot be used to modify
the contents it points-to.
Algorithm:
• Declare a string
• Try to iterate the string using all types of iterators
• Try modification of the element of the string.
• Display all the iterations.
Example:
#include <iostream>
#include <vector>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
std::vector<int> vec = {10, 20, 30, 40, 50};
std::cout << "Array: ";
©Topperworld
C++ Programming
for (int *ptr = std::begin(numbers); ptr !=
std::end(numbers); ++ptr) {
std::cout << *ptr << " ";
}
std::cout << "\nVector: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
return 0;
Output:
Array: 1 2 3 4 5
Vector: 10 20 30 40 50
4) Manipulating Functions
Function Definition
This function copies the substring in the target character
copy(“char
array mentioned in its arguments. It takes 3 arguments,
array”, len,
target char array, length to be copied, and starting
pos)
position in the string to start copying.
swap() This function swaps one string with another
©Topperworld
C++ Programming
Example:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> source = {1, 2, 3, 4, 5};
std::vector<int> destination(source.size());
std::copy(source.begin(), source.end(),
destination.begin());
std::vector<int> first = {10, 20, 30};
std::vector<int> second = {100, 200, 300};
first.swap(second);
std::cout << "Copied: ";
for (int num : destination) std::cout << num << " ";
std::cout << "\nSwapped: ";
for (int num : first) std::cout << num << " ";
std::cout << "| ";
for (int num : second) std::cout << num << " ";
return 0;
}
Output:
Copied: 1 2 3 4 5
Swapped: 100 200 300 | 10 20 30
©Topperworld