cpp / beginner
Snippet
Standard Library Strings
The std::string class from the C++ Standard Library handles text data much more safely than raw character arrays. You can concatenate strings with +, get their length with .length(), and iterate through characters. The toupper function converts individual characters to uppercase. Using std::string is preferred over char arrays for almost all text handling in modern C++.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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;std::cout << "Upper: ";for (char c : greeting) {std::cout << (char)std::toupper(c);}std::endl(std::cout);return 0;}
Breakdown
1
#include <string>
Header file required for std::string class
2
std::string name = "Alice";
Declaration of a string variable holding text
3
+ operator
String concatenation operator joins multiple strings together
4
greeting.length()
Member function returns the number of characters in the string
5
for (char c : greeting)
Range-based for loop iterates through each character in string