</>

✍️ std::string Core Usage for Coding Tests 🚀


What it is: A powerful class that encapsulates character strings, handling memory management and providing a rich set of manipulation functions.

Core Benefit: Safe memory management, a rich feature set for string manipulation, and easy integration with the C++ Standard Library.


✨ Core Operations & Syntax

This section focuses on the functions most frequently required to solve problems.

Operation Code Example Notes
Substring s.substr(pos, len);
s.substr(pos);
Two overloads: substr(pos, len) extracts len chars from pos, substr(pos) extracts from pos to end. Returns a new string (incurs a copy). e.g., s.substr(i, j-i+1) gets substring from index i to j.
Find Substring s.find("world");
s.rfind('o');
find searches from the start, rfind from the end. Returns the starting index or std::string::npos if not found.
Replace s.replace(pos, len, "C++"); Replaces the section of len characters at pos with a new string.
Insert s.insert(pos, "awesome "); Inserts a string at the specified index pos.
Erase s.erase(pos, len); Erases len characters starting from index pos.
C-style String printf("%s", s.c_str()); Returns a const char* pointer, mainly for compatibility with C-style functions.
Append Char s.push_back('!'); Appends a single character to the end of the string. Often efficient.
Remove Last Char s.pop_back(); Removes the last character from the string.
Reserve Memory s.reserve(100); Allocates memory for at least 100 characters to prevent reallocations during repeated appends.

🔄 Common Patterns for Problems

These code snippets solve frequent sub-problems in coding challenges.


💡 Key Use Cases in Contests


🧠 Performance & Best Practices

C++ String Parsing Cheatsheet

1. Headers

#include <string>
#include <vector>
#include <sstream>
#include <iostream>

2. CSV Parsing (String Stream)

Used for parsing arrays (e.g., "0.1, 0.2, 0.3").

std::string raw = "1.0,2.0,3.0";
std::stringstream ss(raw);
std::string segment;
std::vector<double> data;

// getline(stream, string, delimiter)
while (std::getline(ss, segment, ',')) {
    data.push_back(std::stod(segment));
}
std::string data = "100 200 300 400";
std::stringstream ss(data);
std::string token;

while (ss >> token) { // Extracts space-separated tokens
    std::cout << token << std::endl;
}

3. Delimiter Parsing (Find & Substr)

Used for Header/Key-Value pairs (e.g., "VOLT:5.0").

std::string msg = "VOLT:5.0";
size_t pos = msg.find(":"); // Find separator

if (pos != std::string::npos) {
    // substr(start_index) extracts until end
    std::string val = msg.substr(pos + 1); 
}

4. Type Conversions

Function Description Example
std::stoi(str) String to Int int i = std::stoi("100");
std::stod(str) String to Double double d = std::stod("3.14");
std::to_string(val) Number to String std::string s = std::to_string(5);