capypad
0 day streak
cpp / beginner
Snippet

Working with Strings (std::string)

The std::string class provides a powerful way to handle text in C++. Unlike C-style char arrays, std::string automatically manages memory and offers useful methods like length() and substr(). You can concatenate strings using the + operator, making code more readable. The substr() method extracts portions of a string by specifying start position and length.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
 
int main() {
std::string greeting = "Hello";
std::string name = "World";
std::string message = greeting + ", " + name + "!";
std::cout << message << std::endl;
std::cout << "Length: " << message.length() << std::endl;
std::cout << "First char: " << message[0] << std::endl;
std::string sub = message.substr(0, 5);
std::cout << "Substring: " << sub << std::endl;
return 0;
}
Breakdown
1
#include <string>
Header required for std::string class
2
std::string greeting = "Hello";
Declares a string variable initialized with text
3
message = greeting + ", " + name + "!";
Concatenates multiple strings into one
4
message.length()
Returns the number of characters in the string
5
message[0]
Accesses character at index 0 using array syntax
6
message.substr(0, 5)
Extracts 5 characters starting from index 0