Copy One String to Another

Beginner

Introduction

In this lab, you will learn how to copy strings in C++. We will be using both string objects and C-style strings to demonstrate this.

Create a new C++ file

Navigate to the ~/project directory and create a new C++ file named main.cpp.

cd ~/project
touch main.cpp

Copying String Objects

We can use the assignment operator to copy one string object to another. Follow the code below:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string s1, s2;

    cout << "Enter string s1: ";
    getline(cin, s1);

    s2 = s1;

    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2;

    return 0;
}

Explanation:

  • We start by including the necessary libraries for this program which is iostream and string.
  • We then define two string objects s1 and s2
  • The user is prompted to enter the string s1 using the getline() function which reads the entire string with space included.
  • Assign s1 to s2 using the assignment operator.
  • Finally, we print s1 and s2.

Code output

Enter string s1: Hello World!
s1 = Hello World!
s2 = Hello World!

Copying C-Style Strings

We will be using strcpy() function from cstring library to copy C-style strings. Follow the code below:

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char s1[100], s2[100];

    cout << "Enter string s1: ";
    cin.getline(s1, 100);

    strcpy(s2, s1);

    cout << "s1 = " << s1 << endl;
    cout << "s2 = "<< s2;

    return 0;
}

Explanation:

  • We start by including the necessary libraries for this program which is iostream and cstring
  • We then define two C-style string arrays s1 and s2
  • The user is prompted to enter the string s1
  • getline() function is not used in this instance because it is only used for string objects and not C-style strings. Instead, we use cin.getline where the first argument is the array variable, and the second argument is the maximum size of the array to be read.
  • Copy the string s1 to s2 using the strcpy() function in cstring
  • Finally, we print s1 and s2.

Code output

Enter string s1: Hello World!
s1 = Hello World!
s2 = Hello World!

Run the file

To run the code in the terminal, open the terminal in the project folder and execute the following commands:

g++ main.cpp -o main
./main

This command will compile the main.cpp file and outputs an executable file named main in the same directory. The second command runs the main file and outputs the result in the terminal.

Summary

This lab discussed how to copy strings in C++ using string objects and C-style strings. You leant that for string objects, you can use the assignment operator and for C-style strings, you can use the strcpy() function in cstring. By following these simple steps, you can easily copy strings in C++.

Other Tutorials you may like