stl第一部分: string, vector, deque, stack
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
// string 类型的常用方法
|
||||
|
||||
// string 与 char* 的区别
|
||||
|
||||
#include <bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string s1("ism ");
|
||||
string s2("hhhsishg");
|
||||
|
||||
// 拼接
|
||||
// s1 += s2;
|
||||
s1.append(s2);
|
||||
|
||||
/******************
|
||||
// 修改指定位置的内容
|
||||
s1[0] = 'l';
|
||||
|
||||
// 替换
|
||||
// int c_pos = s1.find('h'); // 查找字符 h 的位置
|
||||
// s1.replace(c_pos, 1, "d"); // 替换字符 h 为 d
|
||||
|
||||
// 替换所有的 h 为 d
|
||||
int pos = s1.find('h');
|
||||
cout << "h pos = " << pos << endl;
|
||||
// while (pos != string::npos) // npos 表示查找失败
|
||||
while (pos != -1) // -1 表示查找失败
|
||||
{
|
||||
s1.replace(pos, 1, "d");
|
||||
pos = s1.find("h", pos + 1);
|
||||
}
|
||||
******************/
|
||||
|
||||
// 查找 is 第一次和最后一次出现的位置
|
||||
int is_start = s1.find("is");
|
||||
int is_end = s1.rfind("is");
|
||||
cout << "is_start = " << is_start << endl;
|
||||
cout << "is_end = " << is_end << endl;
|
||||
|
||||
// 查找 is 的长度
|
||||
string s3("is");
|
||||
cout << "is 的长度: " << s3.size() << endl;
|
||||
|
||||
// 清空内容(保留开始和结束的 is)
|
||||
// s1.replace(is_start, is_end - is_start + 2, "");
|
||||
s1.erase(is_start + 2, is_end - is_start - 2);
|
||||
|
||||
cout << s1 << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <bits/stdc++.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
string s1 = "linux c/c++中指针与引用是课程的重点知识";
|
||||
s1.replace(s1.find('/'), 1, "//");
|
||||
cout << s1 << endl;
|
||||
|
||||
s1.erase(2, 5); // 删除从下标为2开始的5个字符
|
||||
s1.insert(2, 5, '*'); // 在下标为2的位置插入5个字符*
|
||||
|
||||
// s1.replace(2, 5, "*****"); // 从下标为2开始的5个字符替换为5个字符*
|
||||
// s1.replace(2, 5, "*****", 2, 3); // 从下标为2开始的5个字符替换为从下标为2开始的3个字符
|
||||
|
||||
cout << s1 << endl;
|
||||
|
||||
string::iterator it = s1.begin();
|
||||
while (it != s1.end())
|
||||
{
|
||||
cout << *it << " "; // 中文字符迭代器无法识别,会输出乱码,因为中文字符 UTF-8 占用3个字节
|
||||
it++;
|
||||
}
|
||||
cout << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user