c++std::string(c++stdstring太长转成c_str乱码)
简介:
C++中的std::string是一个很重要的字符串容器,它提供了方便而高效的字符串操作,同时也是STL中最基本和常用的容器之一。本文将逐级讲解std::string的相关知识点。
一、std::string的定义和初始化
std::string是一个字符串类型的类,使用std::string之前需要包含
1.直接使用一个字符串,将自动进行赋值:
std::string str = "Hello World!";
2.使用另一个std::string进行初始化:
std::string str1 = "Hello";
std::string str2(str1); // copy constructor
3.使用C字符串(char *)进行初始化:
const char* cstr = "Hello World!";
std::string str(cstr);
4.使用重载运算符+连接两个std::string:
std::string str1 = "Hello";
std::string str2 = "World!";
std::string str = str1 + " " + str2;
二、std::string的基本操作
1.访问元素
std::string的元素可以通过下标或迭代器进行访问。
std::string str = "Hello World!";
char ch1 = str[0]; // H
char ch2 = str.at(0); // H
std::string::iterator it = str.begin();
char ch3 = *it; // H
2.插入和删除元素
在std::string中,可以使用insert()、erase()和replace()函数来改变字符串的内容。以下是示例:
std::string str = "Hello World!";
str.insert(6, "beautiful "); // Hello beautiful World!
str.erase(6, 10); // Hello World!
str.replace(0, 5, "Hi"); // Hi World!
3.获取字符串长度和子串
在std::string中,可以使用length()和size()函数来获取字符串长度,substr()函数来获取子串。
std::string str = "Hello World!";
int len = str.length(); // 11
int size = str.size(); // 11
std::string sub1 = str.substr(0, 5); // Hello
std::string sub2 = str.substr(6); // World!
三、std::string的高级操作
1.查找和替换
std::string提供了一些函数来查找和替换子串,如find()、rfind()、replace()等。以下是示例:
std::string str = "Hello World!";
int pos1 = str.find("World"); // 6
int pos2 = str.rfind("o"); // 7
str.replace(pos1, 5, "Universe");// Hello Universe!
2.比较字符串
std::string提供了重载运算符==、!=、<、<=、>和>=来比较字符串,也提供了一些函数如compare()、compare(int pos, int len, const std::string& str)等来比较字符串。以下是示例:
std::string str1 = "Hello";
std::string str2 = "World";
bool equal = (str1 == str2); // false
int compare = str1.compare(str2); // -15
int pos = str1.compare(0, 3, "Hell"); // 0
四、std::string和char *的转换
使用c_str()函数可以将std::string转换为C字符串,使用std::string的构造函数可以将C字符串转换为std::string。
std::string str1 = "Hello";
const char* cstr = str1.c_str(); // "Hello"
std::string str2(cstr); // "Hello"
参考资料:
https://en.cppreference.com/w/cpp/string/basic_string
https://www.tutorialspoint.com/cplusplus/cpp_strings.htm
https://www.geeksforgeeks.org/stdstring-class-in-c/