C++ string类
要想使用string
类,必须在程序中包含头文件string
,string
类位于名称空间std
中
string
类隐藏了字符串的数组性质,让我们能够像处理普通变量那样处理字符串
可以使用如下的方式声明string
对象
string str1; //创建空字符串对象
string str2 = "panther";
可通过cin
将输入读取到str1
中:
cin >> str1;
可以使用数组表示法来访问存储在string
对象中的字符
cout << str2[0];
C++11字符串初始化
可将列表初始化用于string
对象
char first_date[] = {"Le Chapon Dodu"};
char second_date[] = { "2023-01-01" };
string third_date = { "The date" };
string fourth_date = { "Hank's Fine Eats" };
赋值、拼接和附加
可以将一个string
对象赋给另一个string
对象
string str1;
string str2 = "panther";
str1 = str2;
可以使用运算符+
将两个string对象合并起来
string str3;
str3 = str1 + str2;
str1 += str2;
对于C风格字符串,可使用C语言库中的函数来完成这些任务。头文件<cstring>
提供了这些函数
strcpy()
函数将字符串复制到字符数组中
strcat()
函数将字符串附件到字符数组末尾
strlen()
函数返回该字符串包含的字符数
#include <iostream>
#include <string> // make string class available
#include <cstring> // C-style string library
#pragma warning(disable:4996) //防止visual studio报错
int main()
{
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
// assignment for string objects and character arrays
str1 = str2; // copy str2 to str1
strcpy(charr1, charr2); // copy charr2 to charr1
// appending for string objects and character arrays
str1 += " paste"; // add paste to end of str1
strcat(charr1, " juice"); // add juice to end of charr1
// finding the length of a string object and a C-style string
int len1 = str1.size(); // obtain length of str1
int len2 = strlen(charr1); // obtain length of charr1
cout << "The string " << str1 << " contains "
<< len1 << " characters.\n";
cout << "The string " << charr1 << " contains "
<< len2 << " characters.\n";
// cin.get();
return 0;
输出如下:
The string panther paste contains 13 characters.
The string jaguar juice contains 12 characters.
string类读取一行
上面通过cin >> str1;
,将输入存储在string
对象中
但如果要读取一行,可使用getline(cin, str);
如下的例子:
#include <iostream>
#include <string> // make string class available
#include <cstring> // C-style string library
int main()
{
using namespace std;
char charr[20];
string str;
cout << "Length of string in charr before input: "
<< strlen(charr) << endl;
cout << "Length of string in str before input: "
<< str.size() << endl;
cout << "Enter a line of text:\n";
cin.getline(charr, 20); // indicate maximum length
cout << "You entered: " << charr << endl;
cout << "Enter another line of text:\n";
getline(cin, str); // cin now an argument; no length specifier
cout << "You entered: " << str << endl;
cout << "Length of string in charr after input: "
<< strlen(charr) << endl;
cout << "Length of string in str after input: "
<< str.size() << endl;
// cin.get();
return 0;
}
在本人xcode ide中,控制台输出结果如下:
Length of string in charr before input: 0
Length of string in str before input: 0
Enter a line of text:
xiao wang
You entered: xiao wang
Enter another line of text:
zhang san
You entered: zhang san
Length of string in charr after input: 9
Length of string in str after input: 9