In C++, the string is an object of the std::string class that represents a sequence of characters. We can perform many operations on strings, such as concatenation, comparison, conversion, etc.
C++ utilizes string as a sequential collection of characters dedicated to handling textual data storage and manipulation. The primary programming function of strings enables developers to process names along with messages, sentences, and additional textual data in an efficient way. Strings occupy one continuous memory block to store their characters, yet they differ fundamentally from single-valued data types , such as int or char.
Simple String Example
Let us see a simple example of a C++ string.
Example
#include <iostream>
using namespace std; //using the standard namespace
int main( ) {
string s1 = "Hello"; //using string
char ch[] = { 'C', '+', '+'};
string s2 = string(ch); // Convert the character array ch to a string object s2
cout<<s1<<endl; // Output the value of s1 to the console
cout<<s2<<endl; // Output the value of s2 to the console
}
Output:
Hello
C++
Explanation:
The C++ program demonstrates string initialization, where s1 is assigned a string literal, and s2 is created from a character array using the string constructor. After that, it prints both strings as output.
Types of Strings in C++
C++ supports two primary types of strings:
1. C-Style Strings (Character Arrays)
C-style strings contain sequential characters stopped by a terminating null character (\0). The utilization of this string type demands both memory handling functions from the <cstring> library and user-controlled memory management.
Example:
char str[] = "Hello";
2. C++ Strings (std::string from the Standard Library)
Strings processed through std::string demonstrate better flexibility and safety than Standard Template Library (STL). The built-in functions length, append, substr and replace help users efficiently manipulate strings as a matter of standard. Standard Library strings manage memory automatically so developers avoid encountering buffer overflows.
Example:
std::string str = "Hello, C++!";
Creating and Initialize Strings in C++
In C++, strings can be created and initialized using C-style character arrays or std::string from the <string> library.
a. Initializing C-Style Strings:
char str1[] = "Hello"; // Implicit null character '\0'
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicit null character
char str3[10] = "Hello"; // Extra space for modification
b. Initializing std::string:
std::string str1 = "Hello"; // Direct initialization
std::string str2("World"); // Constructor-based initialization
std::string str3(5, 'A'); // Creates "AAAAA"
std::string str4 = str1 + " " + str2; // Concatenation: "Hello World"
Example:
Let us take an example to illustrate the creating and initializing string in C++.
Example
#include <iostream>
#include <string> // Include string library for std::string
int main() {
// (a) Initializing C-Style Strings
char str1[] = "Hello";
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str3[10] = "Hello";
std::cout << "C-Style Strings:" << std::endl;
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
std::cout << "str3: " << str3 << std::endl;
// (b) Initializing std::string
std::string s1 = "Hello";
std::string s2("World");
std::string s3(5, 'A'); // Creates "AAAAA"
std::string s4 = s1 + " " + s2; // Concatenation of s1 and s2
std::cout << "\nstd::string Initialization:" << std::endl;
std::cout << "s1: " << s1 << std::endl;
std::cout << "s2: " << s2 << std::endl;
std::cout << "s3: " << s3 << std::endl;
std::cout << "s4: " << s4 << std::endl;
return 0;
}
Output:
C-Style Strings:
str1: Hello
str2: Hello
str3: Hello
std::string Initialization:
s1: Hello
s2: World
s3: AAAAA
s4: Hello World
Explanation:
The program demonstrates different ways to initialize C-style strings using character arrays and std::string using direct assignment, constructors, and concatenation. It prints the initialized values to show their usage in C++ string handling.
Accessing Strings in C++
String elements can be accessed by their position through indexing in a string. C-style strings access elements through array notation, yet std::string gives users multiple functions to retrieve characters. The traversal methods within loops enable users to manipulate or retrieve information from strings.
a) Accessing C-Style Strings:
Using array indexing:
We can access the C-Style Strings using array indexing in C++.
char str[] = "Hello";
std::cout << str[index];
Using pointers:
We can access the C-Style Strings using pointers in C++.
char str[] = "Hello";
char *ptr = str;
std::cout << *ptr;
b) Accessing std::string:
Using operator:
We can access the std::strings using operator in C++.
std::string str = "Hello";
std::cout << str[index];
Using .at(index):
We can also access the std::strings using .at(index) in C++.
std::cout << str.at(index);
Using .front and .back:
We can also access the std::strings using .front and .back function in C++.
std::cout << str.front(); // First character
std::cout << str.back(); // Last character
Example:
Let us take an example to illustrate the accessing string in C++.
Example
#include <iostream>
#include <string>
int main() {
// Accessing C-Style Strings
char cstr[] = "Hello";
char *ptr = cstr;
std::cout << "C-Style String Access:\n";
std::cout << "Using array indexing: " << cstr[0] << "\n"; // Output: H
std::cout << "Using pointer: " << *ptr << "\n"; // Output: H
std::cout << "Using pointer arithmetic: " << *(cstr + 1) << "\n"; // Output: e
std::cout << "Using loop traversal: ";
for (int i = 0; cstr[i] != '\0'; i++) {
std::cout << cstr[i];
}
std::cout << "\n";
// Accessing std::string
std::string str = "Hello";
std::cout << "\nstd::string Access:\n";
std::cout << "Using [] operator: " << str[1] << "\n"; // Output: e
std::cout << "Using .at(): " << str.at(2) << "\n"; // Output: l
std::cout << "Using .front(): " << str.front() << "\n"; // Output: H
std::cout << "Using .back(): " << str.back() << "\n"; // Output: o
std::cout << "Using iterators: ";
for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
std::cout << *it;
}
std::cout << "\n";
std::cout << "Using range-based for loop: ";
for (char ch : str) {
std::cout << ch;
}
std::cout << "\n";
std::cout << "Using .c_str(): " << str.c_str() << "\n";
return 0;
}
Output:
C-Style String Access:
Using array indexing: H
Using pointer: H
Using pointer arithmetic: e
Using loop traversal: Hello
std::string Access:
Using [] operator: e
Using .at(): l
Using .front(): H
Using .back(): o
Using iterators: Hello
Using range-based for loop: Hello
Using .c_str(): Hello
Explanation:
This C++ program demonstrates various ways to access C-style strings using indexing, pointers, and loops , and std::string using methods like .at, .front, .back, iterators, and range-based loops. It also converts std::string to a C-style string using .c_str.
Updating Strings in C++
A string can be modified by altering specific characters and by adding new sections or substituting existing text. C-style strings need proper memory management during modifications because buffer overflows can occur, while std::string includes automatic functions to add, insert, delete, and swap parts within its strings.
a) Updating C-Style Strings:
Using operator:
In C++, we can update the C-Style string using operator.
char str[] = "Hello";
str[0] = 'M';
std::cout << str; // Output: Mello
b) Updating std::string:
Using or .at:
In C++, we can update the C-Style string using operator.
std::string str = "Hello";
str[0] = 'M';
std::cout << str; // Output: Mello
Example:
Let us take an example to illustrate how to update the string in C++.
Example
#include <iostream>
#include <string> // Include string library for std::string
int main() {
// (a) Updating C-Style String
char cstr[] = "Hello"; // C-style string (character array)
cstr[0] = 'M'; // Modifying the first character
std::cout << "Updated C-Style String: " << cstr << std::endl;
// (b) Updating std::string
std::string str = "Hello"; // Declare a std::string variable
// Using index operator []
str[0] = 'M';
std::cout << "After modifying using []: " << str << std::endl;
// Using .at() method (safe version of indexing)
str.at(1) = 'a';
std::cout << "After modifying using at(): " << str << std::endl;
return 0;
}
Output:
Updated C-Style String: Mello
After modifying using []: Mello
After modifying using at(): Mallo
Explanation:
This C++ program demonstrates updating both C-style strings and std::string in C++. It modifies specific characters using indexing ('') and the '.at' method, showing how string values can be changed safely.
Appending strings using .append or +=
Strings allow new characters or words to be appended to their ends through either C-style manual concatenation or std::string built-in operations.
Using .append method:
We can append the string using the .append method in C++.
std::string str = "Hello";
str.append(" World");
std::cout << str; // Output: Hello World
Using += operator:
We can append the string using the += operator in C++.
std::string str = "Hello";
str += " World";
std::cout << str; // Output: Hello World
Example:
Let us take an example to illustrate how to append the string in C++.
Example
#include <iostream>
#include <string> // Include the string library
int main() {
// Initialize a string
std::string str = "Hello";
// Using .append() to add a word at the end
str.append(" World");
std::cout << "After append(): " << str << std::endl;
// Using += operator to add more text
str += "!!!";
std::cout << "After += operator: " << str << std::endl;
return 0;
}
Output:
After append(): Hello World
After += operator: Hello World!!!
Explanation:
The '.append' method adds " World" to the original string "Hello", updating it to "Hello World". The '+=' operator then further appends "!!!", resulting in the final output "Hello World!!!".
Replacing substrings using .replace
The substring within a string can be exchanged for a different string through direct manual edits in C-style strings and integrated functions in std::string.
std::string str = "Hello World";
str.replace(6, 5, "C++");
std::cout << str; // Output: Hello C++
Example:
Let us take an example to illustrate how to replace the substring using .replace function in C++.
Example
#include <iostream>
#include <string> // Include the string library
int main() {
// Initialize a string
std::string str = "Hello World";
// Using .replace() to replace "World" with "C++"
str.replace(6, 5, "C++");
std::cout << "After replace(): " << str << std::endl;
return 0;
}
Output:
After replace(): Hello C++
Explanation:
The 'std::string::replace' method replaces a portion of the string starting from index '6' with a length of '5' characters (i.e., "World") with "C++". It modifies the original string to "Hello C++", demonstrating how substring replacement works in C++.
Other examples of C++ String
Several another examples of C++ string are as follows:
1. C++ String Compare Example:
Let's see the simple example of string comparison using the strcmp function.
Example
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char key[] = "mango"; // Define the correct answer as a C-string
char buffer[50]; // // Buffer to store user input
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key, buffer) != 0); // Compare input with key;
cout<<"Answer is correct!!"<<endl;
return 0;
}
Output:
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
The answer is correct!!
Explanation:
In this program, the user input is compared with predefined string "mango" using strcmp function. This will check the equality among two strings. When the user inputs "mango", strcmp returns 0, causing the loop to terminate and displaying "Answer is correct!!".
2. C++ String Concat Example:
Let's see the simple example of string concatenation using the strcat function.
Example
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
cout << "Enter the buffer string: ";
cin.getline(buffer, 25);
strcat(key, buffer);
cout << "Key = " << key << endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}
Output:
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.
Explanation:
This program concatenates two C-style strings using the 'strcat' function, which appends the 'buffer' string to the 'key' string. After concatenation, the updated 'key' contains both strings combined, while 'buffer' remains unchanged.
3. C++ String Copy Example:
Let's see the simple example of copying the string using the strcpy function.
Example
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
strcpy(buffer, key);
cout << "Key = "<< key << endl;
cout << "Buffer = "<< buffer<<endl;
return 0;
}
Output:
Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial
Explanation:
This program copies the content of the 'key' string into the 'buffer' string using the 'strcpy' function. After copying, both 'key' and 'buffer' contain the same string.
4. C++ String Length Example:
Let's see the simple example of finding the string length using the strlen function.
Example
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}
Output:
Length of String = 26
Explanation:
This program calculates the length of the string "Welcome to C++ Programming" using the 'strlen' function. It returns the number of characters in the string, excluding the null terminator ('\0').
Pass Strings to Functions in C++
a) Passing C-Style Strings to Functions:
C-style strings are passed as character arrays. It is good practice to use const to prevent modification inside the function.
void printCStr(const char str[]) {
std::cout << str << std::endl;
}
int main() {
char str[] = "Hello";
printCStr(str);
return 0;
}
b) Passing std::string to Functions:
The std::string class provides a safer and more flexible way to handle strings in C++. Passing by reference (const std::string&) avoids unnecessary copies.
#include <iostream>
void printString(const std::string &str) {
std::cout << str << std::endl;
}
int main() {
std::string str = "Hello C++";
printString(str);
return 0;
}
Why Use Strings in C++?
- It sores textual data efficiently
- The string class provides multiple functional capabilities, such as string joining pattern search and substring retrieval.
- The use of std::string provides users with safer memory handling and simplified memory management operations.
C++ String Functions
Here is a table that contains several string functions in C++.
| Function | Description |
|---|---|
| int find(string& str,int pos,int n) | It is used to find the string specified in the parameter. |
| char& at(int pos) | It is used to access an individual character at specified position pos. |
| string& append(const string& str) | It adds new characters at the end of another string object. |
| string& replace(int pos,int len,string& str) | It replaces a portion of the string that begins at character position pos and spans len characters. |
| void resize(int n) | It is used to resize the length of the string up to n characters. |
| int size() | It returns the length of the string in terms of bytes. |
| string substr(int pos,int n) | It creates a new string object of n characters. |
| void swap(string& str) | It is used to swap the values of two string objects. |
| int length() | It is used to find the length of the string. |
| int compare(const string& str) | It is used to compare two string objects. |
| Iterator begin() | It returns the reference of the first character. |
| char& back() | It returns the reference of the last character. |
| int copy(string& str) | It copies the contents of one string into another. |
| string& assign() | It assigns a new value to the string. |
| void pop_back() | It removes the last character of the string. |
| void push_back(char ch) | It adds a new character, ch, at the end of the string. |
| int max_size() | It finds the maximum length of the string. |
| string& insert() | It inserts a new character before the character indicated by the position pos. |
| int findlastnot_of(string& str,int pos) | It searches for the last character that does not match with the specified sequence. |
| int findlastof(string& str,int pos,int n) | It is used to search the string for the last character of a specified sequence. |
| int findfirstnot_of(string& str,int pos,int n ) | It is used to search the string for the first character that does not match with any of the characters specified in the string. |
| int findfirstof(string& str,int pos,int n) | It is used to find the first occurrence of the specified sequence. |
| string& operator=() | It assigns a new value to the string. |
| string& operator+=() | It appends a new character at the end of the string. |
| char& front() | It returns a reference to the first character. |
| string& erase() | It removes the characters as specified. |
| bool empty() | It checks whether the string is empty or not. |
| const_char* data() | It copies the characters of the string into an array. |
| constreverseiterator crbegin() | Icpp tutorials to the last character of the string. |
| void clear() | It removes all the elements from the string. |
| const_iterator cend() | Icpp tutorials to the last element of the string. |
| const_iterator begin() | Icpp tutorials to the first element of the string. |
| int capacity() | It returns the allocated space for the string. |
| char operator[](pos) | It retrieves a character at a specified position pos. |
| char* c_str() | It returns a pointer to an array that contains a null-terminated sequence of characters. |
| int rfind() | It searches for the last occurrence of the string. |
| iterator end() | It references the last character of the string. |
| reverse_iterator rend() | Icpp tutorials to the first character of the string. |
| void shrinktofit() | It reduces the capacity and makes it equal to the size of the string. |
| constreverseiterator crend() | It references the first character of the string. |
| reverse_iterator rbegin() | It references the last character of the string. |
| void reserve(int len) | It requests a change in capacity. |
| allocatortype getallocator(); | It returns the allocated object associated with the string. |
C++ String MCQs
- What is a C++ string?
- A C++ string consists of a character sequence in which integers are stored in arrays.
- A sequence of characters takes residence in a character array that ends with a null terminator character (\0).
- A sequence of characters exists within std::string objects.
- Both B and C
- In C++, which header file allows developers to use std::string?
- <string>
- <cstring>
- <iostream>
- <stdlib.h>
- How does C++ organize string data within storage?
- A collection of integers
- A sequential collection of characters
- A pointer to a single character
- This data type contains only numerical content
- Which character signifies the termination of a C-style string held in C++ memory?
- With a space character
- With a special delimiter
- With a null character (\0)
- With a newline character (\n)
- Which standard function determines the length value of C++ strings utilizing std::string?
- size
- length
- strlen
- Both a and b