String Operations
Part of the Fundamentals section of Coddy's C++ journey — lesson 69 of 74.
In C++, you can concatenate strings using the + operator or the += operator.
For example:
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2;
// Concatenates str1, a space, and str2
std::cout << result;
// Outputs: Hello WorldYou can also use the += operator to append one string to another:
std::string str = "Hello";
str += " ";
str += "World";
std::cout << str;
// Outputs: Hello WorldHere, we start with the string "Hello" and append a space and then "World" using the += operator.
Another common string operation is finding the length of a string. In C++, you can use the length() or size() method to get the number of characters in a string:
std::string str = "Hello";
int len = str.length(); // Or str.size();
std::cout << len; // Outputs: 5The length() and size() methods return the same value - the number of characters in the string.
Challenge
EasyCreate a function named concatenateStrings that takes two std::string arguments, str1 and str2. The function should concatenate str1, a space, and str2 together and return the resulting string. In the main function, declare two strings, firstName and lastName, with your first and last names, respectively. Call concatenateStrings with firstName and lastName as arguments, and store the result in a variable named fullName. Print fullName to the console.
Cheat sheet
In C++, concatenate strings using the + operator:
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2;
// Outputs: Hello WorldUse the += operator to append strings:
std::string str = "Hello";
str += " ";
str += "World";
// Outputs: Hello WorldGet string length using length() or size():
std::string str = "Hello";
int len = str.length(); // Or str.size();
// Returns: 5Try it yourself
#include <iostream>
#include <string>
std::string concatenateStrings(std::string str1, std::string str2) {
// Concatenate the strings and return the result
}
int main() {
std::string firstName;
std::string lastName;
std::getline(std::cin, firstName);
std::getline(std::cin, lastName);
// Call concatenateStrings and store the result in fullName
// Print fullName
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else9Loops
For Loop Part 1While LoopDo While LoopBreakContinueFor Loop Part 2Nested LoopsInfinite LoopsRecap - Dynamic Input12Strings
C-style Strings Part 1C-style Strings Part 2String OperationsString Functions Part 1String Functions Part 2