cpp / beginner
Snippet
String Concatenation and Methods
The string class provides powerful text manipulation. Use + to concatenate strings, length() to get character count, and indexing with [] to access individual characters. The range-based for loop iterates through each character.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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 << "First character: " << fullName[0] << std::endl;std::cout << "Uppercase: ";for (char& c : fullName) {c = std::toupper(c);}std::cout << fullName << std::endl;return 0;}
Breakdown
1
std::string fullName = firstName + " " + lastName;
Concatenates two strings with a space in between
2
fullName.length()
Returns the number of characters in the string
3
fullName[0]
Accesses the first character using zero-based indexing
4
for (char& c : fullName)
Range-based for loop that gives direct reference to each character