Strings: std::string and string_view

স্ট্রিং — std::string ও string_view

Read: ~30 min 20 practice problems

1. Three Kinds of Strings

TypeOwns memory?Use for
const char*NoString literals, C interop
std::stringYesModifiable, heap-managed strings
std::string_viewNo (C++17)Read-only views — fast pass without copy

2. std::string API

string.cpp
#include <iostream>
#include <string>

int main() {
    std::string s = "Hello";
    s += ", world!";
    std::cout << s << "\n";
    std::cout << "size = "  << s.size()  << "\n";
    std::cout << "first = " << s.front() << "\n";
    std::cout << "sub = "   << s.substr(7, 5) << "\n";
    std::cout << "find = "  << s.find("world") << "\n";
    s.replace(7, 5, "there");
    std::cout << s << "\n";
}

3. std::string_view (C++17)

A non-owning view into a string (or any contiguous char data). Cheap to copy — just a pointer + length. Use as parameters when you don't need to modify and don't need to store.

view.cpp
#include <iostream>
#include <string>
#include <string_view>

size_t countA(std::string_view s) {
    size_t c = 0;
    for (char ch : s) if (ch == 'a') ++c;
    return c;
}

int main() {
    std::string s = "banana";
    const char* lit = "apple";
    std::cout << countA(s) << "\n";     // works on string
    std::cout << countA(lit) << "\n";   // works on const char*
    std::cout << countA("data") << "\n"; // works on literal
}
Lifetime trap A string_view doesn't own its data. If the source string is destroyed, the view dangles.

4. Conversions

convert.cpp
#include <iostream>
#include <string>

int main() {
    int n = std::stoi("42");
    double d = std::stod("3.14");
    std::string s = std::to_string(100);

    std::cout << n << " " << d << " " << s << "\n";
}

5. Small String Optimization (SSO)

Most implementations of std::string store small strings (~15 chars) directly inside the string object — no heap allocation. Only when the string grows large do they allocate. Smart and fast.

6. Practice Problems

  1. Concatenate two strings.
    ✨ Show Answer
    std::string c = a + b;
  2. Get the length of "Bangladesh".
    ✨ Show Answer
    std::string s = "Bangladesh";
    std::cout << s.size(); // 10
  3. Convert a string to uppercase.
    ✨ Show Answer
    #include <cctype>
    for (char& c : s) c = std::toupper(static_cast<unsigned char>(c));
  4. Find the position of "an" in "banana".
    ✨ Show Answer
    std::string("banana").find("an"); // 1
  5. Reverse a string.
    ✨ Show Answer
    std::reverse(s.begin(), s.end());
  6. Why is string_view faster than const std::string&?
    ✨ Show Answer

    string_view works for literals without constructing a temporary std::string. const std::string& would force allocation when called with a literal.

  7. Convert "100" to int.
    ✨ Show Answer
    int n = std::stoi("100");
  8. Split "a,b,c" by ',' into a vector.
    ✨ Show Answer
    std::vector<std::string> parts;
    std::string s = "a,b,c", item;
    std::stringstream ss(s);
    while (std::getline(ss, item, ',')) parts.push_back(item);
  9. Check if a string starts with "http".
    ✨ Show Answer
    s.starts_with("http"); // C++20
  10. Get a substring from position 4, length 3.
    ✨ Show Answer
    s.substr(4, 3);
  11. Why are string literals const char*?
    ✨ Show Answer

    They live in read-only memory. Modifying them is undefined behavior. const reflects this.

  12. Append "!" to a string.
    ✨ Show Answer
    s += "!"; // or s.push_back('!') for one char
  13. Trim leading whitespace.
    ✨ Show Answer
    s.erase(0, s.find_first_not_of(" \t\n"));
  14. Show that "hi" == "hi" may be false in C.
    ✨ Show Answer

    For const char*, == compares pointers, not contents. Two literals may have the same address (compiler-dependent). Use strcmp for C-strings or just use std::string where == compares contents.

  15. Build a string with std::format (C++20).
    ✨ Show Answer
    std::string s = std::format("x={} y={}", 3, 4);
  16. Convert std::string to const char* for a C API.
    ✨ Show Answer
    s.c_str();
  17. Erase the third character.
    ✨ Show Answer
    s.erase(2, 1);
  18. Why prefer std::string_view in API parameters?
    ✨ Show Answer

    Accepts string, char*, literal — no copy, no allocation. Best fit when the function only reads.

  19. When is string_view dangerous?
    ✨ Show Answer

    Storing one as a member: if the source string is destroyed, the view dangles. Don't store; pass.

  20. Compare two strings for equality.
    ✨ Show Answer
    if (s1 == s2) {/* same content */}

Summary

Use std::string for owned, modifiable strings. Use std::string_view for read-only parameters — it accepts strings and literals without copying. C-style const char* is for C interop only. Modern std::format (C++20) replaces sprintf safely.

Next Module → Dynamic Memory: new/delete vs Smart Pointers.