# C++ 程序：复制字符串

> 原文： [https://www.programiz.com/cpp-programming/examples/string-copy](https://www.programiz.com/cpp-programming/examples/string-copy)

#### 在此示例中，您将学习如何复制字符串（字符串对象和 C 风格的字符串）。

要理解此示例，您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题：

*   [C++ 数组](/cpp-programming/arrays)
*   [C++ 字符串](/cpp-programming/strings)

* * *

您可以简单地使用`=`赋值运算符在 C++ 中复制字符串对象。

* * *

## 示例 1：复制字符串对象

```cpp
#include <iostream>
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;
} 
```

**输出**

```cpp
Enter string s1: C++ Strings
s1 = C++ Strings
s2 = C++ Strings
```

要在 C++ 中复制 C 字符串，请使用`strcpy()`函数。

* * *

## 示例 1：复制 C 字符串

```cpp
#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;
} 
```

**输出**

```cpp
Enter string s1: C-Strings
s1 = C-Strings
s2 = C-Strings
```