cpp / beginner
Snippet
Working with std::string
The std::string class from the C++ standard library handles text operations easily. You can concatenate strings with +, append with +=, measure length, extract substrings, and search within strings. It manages memory automatically, unlike raw C-strings.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>#include <string>int main() {std::string firstName = "Max";std::string lastName = "Mueller";std::string fullName = firstName + " " + lastName;std::cout << "Full name: " << fullName << std::endl;std::cout << "Length: " << fullName.length() << std::endl;std::cout << "Size: " << fullName.size() << std::endl;std::string greeting = "Hello";greeting += ", World!";std::cout << greeting << std::endl;std::string phrase = "The quick brown fox";std::string sub = phrase.substr(4, 5);std::cout << "Substring: " << sub << std::endl;if (phrase.find("quick") != std::string::npos) {std::cout << "Found 'quick' in phrase!" << std::endl;}return 0;}
Breakdown
1
std::string firstName = "Max";
Creates a string variable to store text, initialized with the value "Max"
2
fullName = firstName + " " + lastName;
Concatenates multiple strings together using the + operator for joining
3
greeting += ", World!";
Appends the string ", World!" to the existing greeting string using the += operator
4
phrase.substr(4, 5)
Extracts a substring starting at position 4 with length 5 characters, returning "quick"
5
phrase.find("quick") != std::string::npos
Searches for "quick" in the phrase, checking if it was found (npos means 'not position', indicating not found)