qfedu-cpp-level/day9/stl_string_demo/d1.cpp

55 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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;
}