C++ 字符串操作全解析
1. 字符串输入与复制
在 C++ 中,字符串操作是常见且重要的任务。首先来看字符串的输入,程序会提示用户输入字符串,每行以 Enter 键结束,直到输入 $
为止。例如:
Enter a string:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty’s orient deep
These flowers, as in their causes, sleep.
$
You entered:
Ask me no more where Jove bestows
When June is past, the fading rose;
For in your beauty’s orient deep
These flowers, as in their causes, sleep.
接下来探讨字符串的复制,有两种方式:
1.1 手动复制字符串
手动复制字符串能让我们深入理解字符串的本质,通过逐字符处理来完成复制。以下是示例代码:
// strcopy1.cpp
// copies a string using a for loop
#include <iostream>
#include <cstring> //for strlen()