Menu
Coddy logo textTech

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 World

You can also use the += operator to append one string to another:

std::string str = "Hello";
str += " ";
str += "World";
std::cout << str;
// Outputs: Hello World

Here, 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: 5

The length() and size() methods return the same value - the number of characters in the string.

challenge icon

Challenge

Easy

Create 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 World

Use the += operator to append strings:

std::string str = "Hello";
str += " ";
str += "World";
// Outputs: Hello World

Get string length using length() or size():

std::string str = "Hello";
int len = str.length(); // Or str.size();
// Returns: 5

Try 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;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals