In C++, the string datatype is an instance of the std::string class which signifies a series of characters. Various tasks can be carried out on strings like merging, contrasting, transforming, and more.
C++ makes use of strings as an ordered set of characters specifically designed for managing text-related data storage and manipulation tasks. The core purpose of strings in programming is to facilitate the handling of names, messages, sentences, and other text-based information effectively. Unlike single-value data types like int or char, strings are stored in a contiguous memory block to hold their characters.
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++ code showcases string initialization, with s1 being set to a string literal and s2 being generated from a character array using the string constructor. Subsequently, it displays both strings as the program output.
Types of Strings in C++
C++ supports two primary types of strings:
1. C-Style Strings (Character Arrays)
C-style strings consist of a series of characters that end with a null character (\0). Working with this type of string requires using memory management functions provided by the standard C library and manual memory management by the programmer.
Example:
char str[] = "Hello";
2. C++ Strings (std::string from the Standard Library)
Strings manipulated using the std::string class exhibit enhanced adaptability and security compared to the Standard Template Library (STL). Essential functions like length, append, substr, and replace empower users to effectively handle strings as a standard practice. The automatic memory management by Standard Library strings effectively prevents developers from facing buffer overflow issues.
Example:
std::string str = "Hello, C++!";
Creating and Initialize Strings in C++
In C++, strings can be generated and set up using C-style arrays of characters or std::string from the standard 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's consider an example to demonstrate the process of creating and initializing a 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 code showcases various methods of initializing C-style strings through character arrays and std::string using direct assignment, constructors, and string concatenation. It displays the assigned values to illustrate their application in C++ string manipulation.
Accessing Strings in C++
String elements can be retrieved based on their position using indexing in a string. While C-style strings use array notation for this purpose, std::string provides various functions for accessing characters. Users can utilize traversal techniques within loops to interact with and extract data from strings.
a) Accessing C-Style Strings:
Using array indexing:
C-Style Strings can be accessed in C++ by using array indexing.
char str[] = "Hello";
std::cout << str[index];
Using pointers:
We can retrieve C-Style Strings by utilizing pointers in C++.
char str[] = "Hello";
char *ptr = str;
std::cout << *ptr;
b) Accessing std::string:
Using operator:
We have the capability to retrieve elements from std::strings by utilizing the operator in C++.
std::string str = "Hello";
std::cout << str[index];
Using .at(index):
We can retrieve the std::strings by utilizing .at(index) in C++.
std::cout << str.at(index);
Using .front and .back:
We have the option to retrieve elements from std::strings by utilizing the .front and .back methods in C++.
std::cout << str.front(); // First character
std::cout << str.back(); // Last character
Example:
Let's consider an example to demonstrate string manipulation 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++ code showcases different methods for interacting with C-style strings such as indexing, pointers, and loops, as well as std::string through functions like .at, .front, .back, iterators, and range-based loops. Additionally, it includes the conversion of std::string to a C-style string using .c_str.
Updating Strings in C++
A string can undergo changes by adjusting certain characters and incorporating new segments or replacing existing text. Proper memory handling is crucial when modifying C-style strings to prevent buffer overflows, whereas std::string offers built-in methods for automatically adding, inserting, removing, and exchanging sections within its strings.
a) Updating C-Style Strings:
Using operator:
In C++, we have the ability to modify C-Style strings using the operator.
char str[] = "Hello";
str[0] = 'M';
std::cout << str; // Output: Mello
b) Updating std::string:
Using or .at:
In C++, we have the ability to modify C-Style strings using the operator.
std::string str = "Hello";
str[0] = 'M';
std::cout << str; // Output: Mello
Example:
Let's consider a scenario to demonstrate the process of modifying a 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++ code showcases the process of altering C-style strings and std::string in C++. It adjusts individual characters by utilizing indexing ('') and the '.at' function, illustrating a secure method of updating string contents.
Appending strings using .append or +=
Strings enable the addition of new characters or words at their ends using either manual concatenation in C-style or built-in operations provided by std::string.
Using .append method:
We have the capability to concatenate strings by utilizing the .append function in C++.
std::string str = "Hello";
str.append(" World");
std::cout << str; // Output: Hello World
Using += operator:
We can concatenate strings by using the += operator in C++.
std::string str = "Hello";
str += " World";
std::cout << str; // Output: Hello World
Example:
Let's consider a scenario to demonstrate the process of adding a 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 method '.append' concatenates " World" to the initial string "Hello", transforming it into "Hello World". Subsequently, the operator '+=' appends "!!!", leading to the ultimate result of "Hello World!!!".
Replacing substrings using .replace
The part of a string can be replaced with another string by directly modifying C-style strings or using built-in functions in std::string.
std::string str = "Hello World";
str.replace(6, 5, "C++");
std::cout << str; // Output: Hello C++
Example:
Let's consider a scenario to demonstrate the process of substituting a substring using the .replace method 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' function updates a segment of the string beginning at index '6' with a size of '5' characters (e.g., "World") by substituting it with "C++". This operation transforms the initial string into "Hello C++", illustrating the concept of replacing substrings in C++.
Other examples of C++ String
Several additional instances of C++ string are provided below:
1. C++ String Compare Example:
Explore an elementary illustration of comparing strings by employing 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 script, the input provided by the user is matched against the predefined string "mango" using the strcmp function. This function is responsible for verifying the equality between two strings. Upon entering "mango", strcmp will yield a result of 0, leading to the conclusion of the loop and the output of "Answer is correct!!".
2. C++ String Concat Example:
Let's explore a basic illustration of string concatenation by utilizing 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 software combines two C-style strings by utilizing the 'strcat' function, which adds the content of the 'buffer' string to the end of the 'key' string. Following this process, the 'key' variable holds the merged strings, leaving the 'buffer' string unaltered.
3. C++ String Copy Example:
Let's explore a straightforward illustration of duplicating a string by employing 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 script duplicates the information from the 'key' string to the 'buffer' string by employing the 'strcpy' function. Subsequently, both 'key' and 'buffer' strings store identical content.
4. C++ String Length Example:
Let's explore a basic example demonstrating how to determine the length of a string by utilizing 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 software computes the size of the string "Welcome to C++ Programming" by utilizing the 'strlen' function, which provides the count 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 transferred as arrays of characters. It is considered a best practice to employ const to avoid alterations within 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 offers a more secure and adaptable method for managing strings in C++. Using pass by reference (const std::string&) helps prevent redundant 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 showcasing various string manipulation 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_PRESERVE36__ | 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