ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# C++ 中的字符串 > 原文: [https://beginnersbook.com/2017/08/strings-in-c/](https://beginnersbook.com/2017/08/strings-in-c/) 字符串是由字符组成的单词,因此它们被称为字符序列。在 C++ 中,我们有两种方法来创建和使用字符串:1)通过创建`char`数组并将它们视为字符串 2)通过创建`string`对象 让我们先讨论这两种创建字符串的方法,然后我们会看到哪种方法更好,为什么。 ## 1)字符数组 - 也称为 C 字符串 **例 1:** 一个简单例子,我们在声明期间初始化了`char`数组。 ```cpp #include <iostream> using namespace std; int main(){ char book[50] = "A Song of Ice and Fire";   cout<<book; return 0; } ``` **输出:** ```cpp A Song of Ice and Fire ``` **示例 2:将用户输入作为字符串** 这可以被视为读取用户输入的低效方法,为什么?因为当我们使用`cin`读取用户输入字符串时,只有字符串的第一个单词存储在`char`数组中而其余部分被忽略。`cin`函数将字符串中的空格视为分隔符,并忽略其后的部分。 ```cpp #include <iostream> using namespace std; int main(){ char book[50]; cout<<"Enter your favorite book name:"; //reading user input cin>>book; cout<<"You entered: "<<book; return 0; } ``` **输出:** ```cpp Enter your favorite book name:The Murder of Roger Ackroyd You entered: The ``` 你可以看到只有`The`被捕获在`book`中,空格之后的剩下部分被忽略。那怎么处理呢?那么,为此我们可以使用`cin.get`函数,它读取用户输入的完整行。 **示例 3:使用 `cin.get`** 正确捕获用户输入字符串的方法 ```cpp #include <iostream> using namespace std; int main(){ char book[50]; cout<<"Enter your favorite book name:"; //reading user input cin.get(book, 50); cout<<"You entered: "<<book; return 0; } ``` **输出:** ```cpp Enter your favorite book name:The Murder of Roger Ackroyd You entered: The Murder of Roger Ackroyd ``` ### 这种方法的缺点 1)`char`数组的大小是固定的,这意味着通过它创建的字符串的大小是固定大小的,在运行时期间不能分配更多的内存。例如,假设您已创建一个大小为 10 的字符数组,并且用户输入大小为 15 的字符串,则最后五个字符将从字符串中截断。 另一方面,如果您创建一个更大的数组来容纳用户输入,那么如果用户输入很小并且数组比需要的大得多,则会浪费内存。 2)在这种方法中,你只能使用为数组创建的内置函数,它们对字符串操作没有多大帮助。 **这些问题的解决方案是什么?** 我们可以使用字符串对象创建字符串。让我们看看我们如何做到这一点。 ## C++ 中的`string`对象 到目前为止我们已经看到了如何使用`char`数组处理 C++ 中的字符串。让我们看看在 C++ 中处理字符串的另一种更好的方法 - 字符串对象。 ```cpp #include<iostream> using namespace std; int main(){ // This is how we create string object string str; cout<<"Enter a String:"; /* This is used to get the user input * and store it into str */ getline(cin,str); cout<<"You entered: "; cout<<str<<endl; /* This function adds a character at * the end of the string */ str.push_back('A'); cout<<"The string after push_back: "<<str<<endl; /* This function deletes a character from * the end of the string */ str.pop_back(); cout << "The string after pop_back: "<<str<<endl; return 0; } ``` **输出:** ```cpp Enter a String:XYZ You entered: XYZ The string after push_back: XYZA The string after pop_back: XYZ ``` 使用这种方法的好处是你不需要声明字符串的大小,大小是在运行时确定的,所以这是更好的内存管理方法。内存在运行时动态分配,因此不会浪费内存。