string基本概念
-
本质
- 是一个类
- char*是一个指针
- 封装了很多成员方法find 、 copy、delete、replace、insert
-
构造函数
-
string();
string(const char* s);
-
stirng(const string& str);
-
string (int n, char c);
-
void test01()
{
std::string s1;//default constructor
const char* str = "hello world";
std::string s2(str);// 有参构造
std::string s3(s2);// copy constructor
string s4(10, 'a');// 有参构造
cout << "s1:" << s1 <<"\n"
<<"s2:"<< s2 << "\n"
<<"s3:"<< s3 << "\n"
<<"s4:"<< s4 << endl;
}
赋值操作
void test01()
{
string str1, str2, str3;
//等号赋值
str1 = "hello world";
str2 = str1;
str3 = 'a';
cout << "s1:" << str1 << "\n"
<< "s2:" << str2 << "\n"
<< "s3:" << str3 << endl;
//assign 赋值
str1.assign("hello world!");
str2.assign("hello world!", 5);
str3.assign(str2);
string str4;
str4.assign(10, 'a');
cout << "s1:" << str1 << "\n"
<< "s2:" << str2 << "\n"
<< "s3:" << str3 << "\n"
<< "s4:" <<str4 << endl;
}
字符串拼接
void test01()
{
string str1 = "I ";
str1 += "love playing game";
str1 += '!';
string str2 = "such as DNF";
str1 += str2;
str1.append(" and LOL");
str1.append(" :)! m ===", 3);
string str3 = "\nBut now";
str1.append(str3);
string str4 = "sda I love kkssdaqweea";
str1.append(str4, 3, 8);//起始位置, 字符串长度;
str1.append("you more!");
cout << str1 << endl;
}
查找和替换
void test01()
{
string str1 = "abcdefg";
int a = str1.find("def");// return the index of result, if not find, return -1, start from begining;
int b = str1.rfind("def");// return the index of result, if not find, return -1, start from end;
str1.replace(a, b, "1111"); //从a下标起, b个字符串被替换为目标字符串
cout << str1 << endl;
}
字符串比较
- = return 0
- < return 1
- > return -1
void test01()
{
string str1 = "hello";
string str2 = "c++";
cout << str1.compare(str2) << endl;//比较首字母大小,最大意义是比较两个字符串相等
}
字符存取
- []
- at
void test01()
{
string str = "hello";
for (int i = 0; i < str.size(); i++)
{
cout << str[i];
cout << str.at(i);
}
cout << endl;
str[2] = 'y';
str.at(3) = ' ';
str.pop_back();
cout << str << endl;
}
插入和删除
void test01()
{
string str = "hello";
str.insert(5, " world");//第五个位置起, 插入" world";
str.erase(0, 6);//第0个位置起,删除6个字符
cout << str << endl;
}
子串
void test01()
{
string str = "hello@163.com";
int pos = str.find("@");
string subStr = str.substr(0, pos);
cout << subStr << endl;
}