string


Header: <string>

The <string> header is a fundamental part of the C++ Standard Library, providing the std::string class and related functions for string manipulation.

Key Characteristics

Example 1: Basic String Operations

#include <iostream>
#include <string>

int main() {
    std::string s1 = "Hello";
    std::string s2 = " World";

    // Concatenation
    std::string s3 = s1 + s2;

    // Substring
    std::string sub = s3.substr(0, 5);

    // Length
    size_t len = s3.length();

    std::cout << "Concatenated: " << s3 << std::endl;
    std::cout << "Substring: " << sub << std::endl;
    std::cout << "Length: " << len << std::endl;

    return 0;
}

Example 2: String Modification

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World";

    // Append
    str.append("!");

    // Insert
    str.insert(5, " Beautiful");

    // Replace
    str.replace(0, 5, "Greetings");

    // Erase
    str.erase(str.find("World"), 5);

    std::cout << str << std::endl;

    return 0;
}

Example 3: String Searching

#include <iostream>
#include <string>

int main() {
    std::string str = "The quick brown fox jumps over the lazy dog";

    // Find substring
    size_t pos = str.find("fox");
    if (pos != std::string::npos) {
        std::cout << "Found 'fox' at position: " << pos << std::endl;
    }

    // Find character
    pos = str.find_first_of("aeiou");
    if (pos != std::string::npos) {
        std::cout << "First vowel at position: " << pos << std::endl;
    }

    return 0;
}

Example 4: String Conversion

#include <iostream>
#include <string>

int main() {
    // String to number
    std::string numStr = "123";
    int num = std::stoi(numStr);

    // Number to string
    double pi = 3.14159;
    std::string piStr = std::to_string(pi);

    std::cout << "Converted number: " << num << std::endl;
    std::cout << "Converted string: " << piStr << std::endl;

    return 0;
}

Additional Considerations

  1. Performance: std::string is designed for efficiency, but for very large strings or frequent modifications, consider using std::stringstream or std::string_view (C++17).

  2. Memory Management: std::string handles memory allocation and deallocation automatically.

  3. Thread Safety: std::string is not thread-safe by default. Use proper synchronization when sharing strings across threads.

  4. C-Style Strings: Use c_str() method to get a C-style string (null-terminated) from std::string.

Summary

The <string> header in C++ provides a robust and efficient way to handle strings. It offers a wide range of operations for string manipulation, searching, and conversion. Understanding and effectively using std::string is crucial for handling text data in C++ programs. While it covers most string-related needs, be aware of performance considerations for specific use cases and the availability of newer features like std::string_view in modern C++ standards.

Previous Page | Course Schedule | Course Content