cpp / beginner
Snippet
std::string: Working with Text
std::string is part of the C++ standard library and provides a safe, easy way to work with text. Unlike C-style character arrays, std::string handles memory automatically, can be resized dynamically, and provides useful methods like length(). You can concatenate strings using the + operator.
snippet.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>#include <string>int main() {std::string name = "World";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 type
2
std::string name = "World"
Creates a string variable to store text
3
"Hello, " + name + "!"
Concatenates multiple strings using + operator
4
greeting.length()
Method that returns the number of characters in the string
5
std::endl
Inserts newline and flushes output buffer