内容参考于《21天学通C++》(第八版)
五.C++字符串std::string
1. 示例
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 创建有初始值的字符串
string greetString("Hello std::string!");
cout << greetString << endl;
// 创建空字符串,并获取值
cout << "Enter a line of text: " << endl;
string firstLine;
getline(cin, firstLine);
cout << "Enter another: " << endl;
string secondLine;
getline(cin, secondLine);
// 字符串拼接
cout << "Result of concatenation: " << endl;
string concatString = firstLine + " " + secondLine;
cout << concatString << endl;
// 字符串复杂
cout << "Copy of concatenated string: " << endl;
string aCopy;
aCopy = concatString;
cout << aCopy << endl;
cout << "Length of concat string: " << concatString.length() << endl;
return 0;
}
运行结果
Hello std::string!
Enter a line of text:
6666666666666666666666666666666666
Enter another:
5555555555555555555555555555555555
Result of concatenation:
6666666666666666666666666666666666 5555555555555555555555555555555555
Copy of concatenated string:
6666666666666666666666666666666666 5555555555555555555555555555555555
Length of concat string: 69
2. 作用
这里完全不用考虑字符串的大小,不用考虑内存溢出。