5. string类非成员函数
上面的几个接口大家了解一下,下面的OJ题目中会有一些体现他们的使用。string类中还有一些其他的 操作,这里不一一列举,大家在需要用到时不明白了查文档即可。
试用rfind、substr、find、find_first_(not)_of
void test_string9()
{
//string s1("file.cpp");
string s1("file.c.tar.zip");
// 拿到文件的后缀
size_t pos1 = s1.rfind('.');
if (pos1 != string::npos)
{
string suffix = s1.substr(pos1);
//string suffix = s1.substr(pos1, s1.size()-pos1);
cout << suffix << endl;
}
else
{
cout << "没有后缀" << endl;
}
string url2("https://legacy.cplusplus.com/reference/string/string/substr/");
string url1("http://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=65081411_1_oem_dg&wd=%E5%90%8E%E7%BC%80%20%E8%8B%B1%E6%96%87&fenlei=256&rsv_pq=0xc17a6c03003ede72&rsv_t=7f6eqaxivkivsW9Zwc41K2mIRleeNXjmiMjOgoAC0UgwLzPyVm%2FtSOeppDv%2F&rqlang=en&rsv_dl=ib&rsv_enter=1&rsv_sug3=4&rsv_sug1=3&rsv_sug7=100&rsv_sug2=0&rsv_btype=i&inputT=1588&rsv_sug4=6786");
string protocol, domain, uri;
size_t i1 = url1.find(':');
if (i1 != string::npos)
{
protocol = url1.substr(0, i1 - 0);
cout << protocol << endl;
}
// strchar
size_t i2 = url1.find('/', i1 + 3);
if (i2 != string::npos)
{
domain = url1.substr(i1 + 3, i2 - (i1 + 3));
cout << domain << endl;
uri = url1.substr(i2 + 1);
cout << uri << endl;
}
// strstr
size_t i3 = url1.find("baidu");
cout << i3 << endl;
std::string str("Please, replace the vowels in this sentence by asterisks.");
cout << str << endl;
// strtok
std::size_t found = str.find_first_not_of("aeiou");
while (found != std::string::npos)
{
str[found] = '*';
found = str.find_first_not_of("aeiou", found + 1);
}
cout << str << endl;
cout << (url1 < url2) << endl;
string ss1 = "xxx";
string ss2 = "yyy";
string ret = ss1 + ss2;
cout << ret << endl;
string ret1 = ss1 + "yyyy";
string ret2 = "yyyy" + ss2;
}
试用assign、insert、erase、swap
void test_string10()
{
string s1("xhello world");
cout << s1 << endl;
s1.assign(" xxxxx");
cout << s1 << endl;
s1.insert(0, "yyyy");
cout << s1 << endl;
s1.erase(5, 3);
cout << s1 << endl;
s1.erase();
cout << s1 << endl;
string s2("hello world hello bit");
/*s2.replace(5, 1, "20%");
cout << s2 << endl;*/
/*size_t pos = s2.find(' ');
while (pos != string::npos)
{
s2.replace(pos, 1, "20%");
pos = s2.find(' ');
}
cout << s2 << endl;*/
// insert/erase/replace
// 能少用就要少用,因为基本都要挪动数据,效率不高
string s3;
s3.reserve(s2.size());
for (auto ch : s2)
{
if (ch != ' ')
{
s3 += ch;
}
else
{
s3 += "20%";
}
}
cout << s3 << endl;
s2.swap(s3);
cout << s2 << endl;
}