C++

Strings in C++

In C++, a String is a collection of characters used to represent text. Theoretically, C++ handles strings in two distinct ways: the traditional C-Style String (inherited from the C language) and the modern std::string Class (part of the Standard Template Library).

1. The Theory: Two Approaches to Text

To understand strings in C++, you must understand the evolution of how text is stored in memory.

A. C-Style Strings (The Array Approach)

Theoretically, a C-style string is simply a One-Dimensional Array of characters (char).

  • The Null Terminator (\0): This is the most critical theoretical concept. C-style strings are "Null-terminated." To know where a string ends, C++ places a special hidden character \0 at the very end.

  • Memory: If you store "Hi", the array must be size 3: ['H', 'i', '\0'].

  • Risk: They are fixed in size and prone to buffer overflows.

B. std::string Class (The Object Approach)

Modern C++ uses the std::string class from the <string> header.

  • Dynamic Memory: Unlike arrays, std::string objects can grow or shrink in size automatically during runtime.

  • Safety: It manages its own memory, meaning you don't have to worry about null terminators or running out of space.

2. Working with std::string

To use modern strings, you must include the #include <string> header.

Featurestd::string MethodDescription
Declarationstring s = "Hello";Initializes a string object.
Concatenations1 + s2Joins two strings together.
Lengths.length() or s.size()Returns the number of characters.
Accesss[0]Accesses a character at a specific index.
Comparison==, !=, <, >Compares strings lexicographically (alphabetical order).

3. Long Theory: String Memory and Performance

A. The "Small String Optimization" (SSO)

Modern C++ compilers use a technique called SSO. For very short strings (usually under 15–23 characters), the string data is stored directly inside the string object on the Stack. For longer strings, the object allocates memory on the Heap. This makes working with short bits of text extremely fast.

B. Input Handling Pitfalls

Standard input using cin >> str; has a theoretical limitation: it stops reading as soon as it encounters a whitespace (space, tab, or newline).

  • The Solution: To read a full line of text (like a full name), we use the getline(cin, str); function.

4. Practical Code Example

#include <iostream>
#include <string> // Essential for std::string
using namespace std;

int main() {
    string firstName, lastName;

    // Input using cin (Stops at space)
    cout << "Enter your first name: ";
    cin >> firstName;

    // Clearing the buffer before getline
    cin.ignore(); 

    // Input using getline (Reads whole line)
    cout << "Enter your full last name (and middle names): ";
    getline(cin, lastName);

    // Concatenation
    string fullName = firstName + " " + lastName;

    cout << "\n--- String Analysis ---" << endl;
    cout << "Full Name: " << fullName << endl;
    cout << "Number of characters: " << fullName.length() << endl;
    cout << "First character: " << fullName[0] << endl;

    // Comparison
    if (firstName == "Admin") {
        cout << "Access Level: Root" << endl;
    } else {
        cout << "Access Level: User" << endl;
    }

    return 0;
}

5. String Functions (Member Functions)

The std::string class comes with built-in "tools" to manipulate text easily:

  • s.append("text"): Adds text to the end.

  • s.substr(start, length): Extracts a part of the string.

  • s.find("text"): Returns the index where a substring starts.

  • s.clear(): Deletes all characters in the string.

  • s.empty(): Returns true if the string has 0 characters.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now