Introduction to C++ | Strings

Strings in C++

In C++, a string is a sequence of characters that represents text. C++ provides two primary ways to handle strings: the traditional C-style strings (arrays of characters) and the C++ std::string class, which is more modern and easier to use.

What is a String in C++?

A string is a collection of characters stored sequentially. In C++, you can use both:

C-Style String

A C-style string is an array of characters with a null terminator (`'0'`) at the end. You can define a C-style string as follows:

Code Example: C-Style String


#include <iostream>
using namespace std;

int main() {
    char str[] = "Hello, World!"; // C-style string
    cout << "String: " << str << endl;
    
    return 0;
}
            

Output

String: Hello, World!

C++ String Class

The std::string class in C++ provides a more flexible and easier-to-use way to handle strings. It is part of the C++ Standard Library and allows you to perform many string-related operations without having to worry about memory management and null-terminators.

Code Example: C++ String


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, C++ World!"; // C++ string
    cout << "String: " << str << endl;
    
    return 0;
}
            

Output

String: Hello, C++ World!

C++ String Functions

Function Description
int compare(const string& str) Used to compare two string objects.
int length() Used to find the length of the string.
void swap(string& str) Swaps the values of two string objects.
string substr(int pos, int n) Creates a new string object of `n` characters starting from position `pos`.
int size() Returns the length of the string in terms of bytes.
void resize(int n) Resizes the length of the string to `n` characters.
string& replace(int pos, int len, string& str) Replaces a portion of the string starting at position `pos` and spanning `len` characters with another string.
string& append(const string& str) Adds new characters at the end of another string object.
char& at(int pos) Accesses an individual character at the specified position `pos`.
int find(string& str, int pos, int n) Finds the string specified in the parameter.
int find_first_of(string& str, int pos, int n) Finds the first occurrence of the specified sequence.
int find_first_not_of(string& str, int pos, int n) Searches the string for the first character that does not match any of the characters specified in the string.
int find_last_of(string& str, int pos, int n) Searches the string for the last character of the specified sequence.
int find_last_not_of(string& str, int pos) Searches for the last character that does not match with the specified sequence.
string& insert() Inserts a new character before the character indicated by the position `pos`.
int max_size() Finds the maximum length of the string.
void push_back(char ch) Adds a new character `ch` at the end of the string.
void pop_back() Removes the last character of the string.
string& assign() Assigns a new value to the string.
int copy(string& str) Copies the contents of a string into another.
char& back() Returns the reference of the last character.
Iterator begin() Returns the reference to the first character of the string.
int capacity() Returns the allocated space for the string.
const_iterator cbegin() It points to the first element of the string.

Common String Operations in C++

Example: 1.String Initialization

Code Example: String Initialization


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "C++ Programming";
    string emptyStr;

    cout << "String 1: " << str1 << endl;
    cout << "String 2: " << str2 << endl;
    cout << "Empty String: " << emptyStr << endl;

    return 0;
}
        

Output

String 1: Hello
String 2: C++ Programming
Empty String:

Example: 2.Concatenation and Length

Code Example: Concatenation and Length


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "Hello";
    string str2 = "World!";
    
    // Concatenation
    string result = str1 + ", " + str2;
    
    // Length
    int length = result.length();
    
    cout << "Concatenated String: " << result << endl;
    cout << "Length of the String: " << length << endl;
    
    return 0;
}
            

Output

Concatenated String: Hello, World!
Length of the String: 13

Example: 3.Appending Strings

Code Example: Appending Strings


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello";
    str.append(", World!");

    cout << "Appended String: " << str << endl;

    return 0;
}
        

Output

Appended String: Hello, World!

Example: 4 Accessing Characters

Code Example: Accessing Characters


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "C++ Programming";
    
    cout << "First Character: " << str[0] << endl;
    cout << "Last Character: " << str[str.length() - 1] << endl;
    
    return 0;
}
            

Output

First Character: C
Last Character: g

Example: 5.Finding Substring

Code Example: Finding Substring


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Programming in C++";
    size_t pos = str.find("C++");

    if (pos != string::npos) {
        cout << "'C++' found at position: " << pos << endl;
    } else {
        cout << "'C++' not found." << endl;
    }

    return 0;
}
        

Output

'C++' found at position: 15

Example: 6.Replacing Substring

Code Example: Replacing Substring


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, World!";
    str.replace(7, 5, "C++");

    cout << "Modified String: " << str << endl;

    return 0;
}
        

Output

Modified String: Hello, C++!

Example: 7.Inserting Substring

Code Example: Inserting Substring


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello!";
    str.insert(5, ", World");

    cout << "Modified String: " << str << endl;

    return 0;
}
        

Output

Modified String: Hello, World!

Example: 8.Erasing Characters

Code Example: Erasing Characters


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, World!";
    str.erase(5, 7);

    cout << "Modified String: " << str << endl;

    return 0;
}
        

Output

Modified String: Hello!

Example: 9.String Capacity

Code Example: String Capacity


#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, C++!";
    
    // Initial capacity
    cout << "Initial Capacity: " << str.capacity() << endl;
    
    // Adding more characters to exceed capacity
    str += " Let's learn string operations.";
    cout << "New Capacity after modification: " << str.capacity() << endl;

    // Reserving more capacity
    str.reserve(100);
    cout << "Capacity after reserve: " << str.capacity() << endl;

    return 0;
}
        

Output

Initial Capacity: 15
New Capacity after modification: 31
Capacity after reserve: 100

Example: 10.Reversing a String

Code Example: Reversing a String


#include <iostream>
#include <string>
#include <algorithm> // for reverse()
using namespace std;

int main() {
    string str = "Hello, World!";
    
    // Reverse the string
    reverse(str.begin(), str.end());

    cout << "Reversed String: " << str << endl;

    return 0;
}
        

Output

Reversed String: !dlroW ,olleH

Pro Tip:

💡 Pro Tip

When using strings in C++, the std::string class is preferred because it is more flexible and easier to use than C-style strings. C++ strings handle memory automatically, reducing the risk of memory errors.