一、字符串的定义与赋值
C++中使用string库来定义字符串变量,可以通过赋值运算符或者构造函数进行赋值。例如:
#include <string> #include <iostream> using namespace std; int main() { string str1 = "hello world!"; cout << str1 << endl; //输出 hello world! string str2; str2 = "i am a string."; cout << str2 << endl; //输出 i am a string. string str3("c++ string"); cout << str3 << endl; //输出 c++ string return 0; }
二、字符串的拼接与比较
使用加号运算符进行字符串的拼接,使用== 或者!= 运算符进行字符串的比较。例如:
#include <string> #include <iostream> using namespace std; int main() { string str1 = "hello"; string str2 = "world!"; string str3; str3 = str1 + " " + str2; if(str3 == "hello world!") cout << "str3 等于 hello world!" << endl; return 0; }
三、字符串的截取与查找
使用substr函数可以实现对字符串的截取操作,通过find函数可以定位字符串中某一字符或者子串出现的位置。例如:
#include <string> #include <iostream> using namespace std; int main() { string str1 = "hello world!"; string subStr = str1.substr(6, 5); //截取子串:world int pos = str1.find("o"); //定位字符 o 第一次出现的位置 cout << subStr << endl; cout << pos << endl; return 0; }
四、字符串与C风格字符串的转换
由于C++标准库中string类型与C语言中的字符串表达不同,因此在C++开发中有时需要进行二者的转换,例如:
#include <string> #include <iostream> #include <cstring> using namespace std; int main() { string str1 = "hello world!"; const char* cstr = str1.c_str(); char cstrArray[20]; strcpy(cstrArray, cstr); cout << cstrArray << endl; //输出 hello world! return 0; }
五、字符串的遍历
可以使用迭代器、下标运算符等方式遍历字符串中的每一个字符。例如:
#include <string> #include <iostream> using namespace std; int main() { string str1 = "hello world!"; for(int i = 0; i < str1.size(); i++) cout << str1[i] << endl; cout << "---------------------" << endl; for(auto it = str1.begin(); it != str1.end(); it++) cout << *it << endl; return 0; }
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/246498.html