C++ Strings

Working with text and string manipulation in C++

๐Ÿ“ What are C++ Strings?

C++ strings are objects that represent sequences of characters. They provide powerful methods for text manipulation, concatenation, searching, and formatting text data efficiently.


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

int main() {
    string greeting = "Hello, World!";
    cout << greeting << endl;
    cout << "Length: " << greeting.length() << endl;
    return 0;
}
                                    

Output:

Hello, World!
Length: 13

C++ String Features

๐Ÿ”ค

Declaration

Create and initialize strings

string name = "Alice";
string empty = "";
โž•

Concatenation

Join strings together

string full = first + " " + last;
text += " more text";
๐Ÿ“

Length

Get string size and properties

int len = text.length();
bool empty = text.empty();
๐Ÿ”

Access

Access individual characters

char first = name[0];
char last = name.at(4);

๐Ÿ”น String Declaration and Input

The std::string class from the <string> header provides a safe, flexible way to handle text. Declare strings with std::string name = "Hello";. For input, std::cin >> str reads a single word, stopping at whitespace. To read a full line with spaces, use std::getline(std::cin, str). Always be mindful of mixing cin >> and getline, as leftover newlines can cause issuesโ€”clear the input buffer with std::cin.ignore() when necessary.

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

int main() {
    // Different ways to create strings
    string message = "Hello";
    string name;
    string greeting("Welcome!");
    
    cout << "Enter your name: ";
    getline(cin, name);  // Read full line with spaces
    
    cout << message << " " << name << "!" << endl;
    cout << greeting << endl;
    
    return 0;
}

Output:

Enter your name: John Doe
Hello John Doe!
Welcome!

๐Ÿ”น String Concatenation

String Concatenation combines multiple C-style strings into one using functions like strcat(), enabling dynamic text assembly. Starting with "Hello" (length 5), adding " Alice" forms "Hello Alice" (length 11), and appending "!" finalizes the message. This process is essential for building user messages, log entries, or SQL queries, though it requires careful buffer sizing to avoid overflow. It highlights the importance of memory safety and efficient string handling in system-level applications.

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

int main() {
    string first = "Hello";
    string second = "World";
    
    // Using + operator
    string combined = first + " " + second + "!";
    cout << combined << endl;
    
    // Using += operator
    string message = "Good";
    message += " ";
    message += "Morning";
    cout << message << endl;
    
    // Using append method
    string text = "C++";
    text.append(" Programming");
    cout << text << endl;
    
    return 0;
}

Output:

Hello World!
Good Morning
C++ Programming

๐Ÿ”น String Methods

std::string offers a rich set of methods for manipulation, searching, and inspection. Key functions include .length() or .size() for length, .find() for searching substrings, .substr() for extracting parts, and .replace() for modifying sections. Methods like .erase() and .insert() change content, while .compare() checks lexicographic order. Modern C++ also provides .starts_with() and .ends_with() (C++20). These methods enable efficient text processing without manual character array handling.

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

int main() {
    string text = "Hello World";
    
    cout << "Original: " << text << endl;
    cout << "Length: " << text.length() << endl;
    cout << "First character: " << text[0] << endl;
    cout << "Last character: " << text[text.length()-1] << endl;
    
    // Substring
    string sub = text.substr(6, 5);  // Start at 6, take 5 chars
    cout << "Substring: " << sub << endl;
    
    // Find
    int pos = text.find("World");
    cout << "Position of 'World': " << pos << endl;
    
    return 0;
}

Output:

Original: Hello World
Length: 11
First character: H
Last character: d
Substring: World
Position of 'World': 6

๐Ÿง  Test Your Knowledge

Which header file is needed to use the string class in C++?