在C++中,string类是一个标准库中的字符串类,可以方便地进行字符串的操作。以下是一些常见的string类的使用方法:
声明和初始化string对象:#include <string>using namespace std;string str1; // 声明一个空的字符串string str2 = "Hello"; // 初始化一个字符串为"Hello"string str3(5, 'A'); // 初始化一个包含5个字符'A'的字符串字符串的输入输出:#include <iostream>#include <string>using namespace std;string str;cin >> str; // 从标准输入获取一个字符串cout << str; // 输出字符串到标准输出字符串的连接:string str1 = "Hello";string str2 = "World";string result = str1 + " " + str2; // 将两个字符串连接起来cout << result; // 输出结果为"Hello World"获取字符串的长度:string str = "Hello";int len = str.length(); // 获取字符串的长度cout << len; // 输出结果为5字符串的查找和替换:string str = "Hello World";int pos = str.find("World"); // 查找字符串中是否包含子串"World"if (pos != string::npos) { cout << "Found at position: " << pos << endl;}str.replace(6, 5, "C++"); // 替换字符串中的一部分cout << str; // 输出结果为"Hello C++"字符串的子串提取:string str = "Hello World";string sub = str.substr(6, 5); // 提取字符串中的一部分cout << sub; // 输出结果为"World"这些只是string类的一些基本使用方法,还有许多其他的操作和函数可以用来处理字符串。详情可以查阅C++的官方文档或参考其他相关资料。




