capypad
0 day streak
cpp / beginner
Snippet

Working with Strings: std::string Basics

The std::string class lets you work with text easily. You can concatenate strings using the + operator, get the length with .length(), and access individual characters. Unlike C-style char arrays, std::string handles memory automatically and grows as needed.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <string>
int main() {
std::string name = "Alice";
std::string greeting = "Hello, " + name + "!";
std::cout << greeting << std::endl;
std::cout << "Length: " << greeting.length() << std::endl;
return 0;
}
Breakdown
1
#include <string>
Header required for std::string class
2
std::string name = "Alice"
Declares and initializes a string variable
3
std::string greeting = "Hello, " + name + "!"
Concatenates multiple strings into one variable