std::string

C++ string class

Interview Relevant: Modern string handling

std::string

The standard C++ string class with automatic memory management.

Code Examples

std::string creation and common operations.

cpp
1#include <string>
2
3// Creation
4string s1 = "Hello";
5string s2("World");
6string s3(5, 'a');  // "aaaaa"
7
8// Concatenation
9string s4 = s1 + " " + s2;  // "Hello World"
10s1 += "!";  // "Hello!"
11
12// Access
13char first = s1[0];      // 'H'
14char last = s1.back();   // '!'
15char safe = s1.at(0);    // 'H' (with bounds checking)
16
17// Properties
18int len = s1.length();   // or size()
19bool empty = s1.empty();
20
21// Comparison
22if (s1 == s2) { }
23if (s1 < s2) { }   // Lexicographic
24
25// Substrings
26string sub = s1.substr(0, 3);  // "Hel"
27
28// Find
29size_t pos = s1.find("llo");  // 2
30if (pos != string::npos) { }
31
32// Iterate
33for (char c : s1) { cout << c; }

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In