void test_string1() //对象的创建
{
string s1;
string s2("haha");
string s3(s2);
s1 = s2;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
}
void test_string2() //将字符串转换为数字
{
string s4("1234");
string::iterator it = s4.begin();
int num = 0;
while (it != s4.end())
{
num *= 10;
num += *it - '0';
++it;
}
cout << num << endl;
}
void test_string3() //使用vector可以直接插入数字
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
vector<int>::iterator vit = v.begin();
while (vit != v.end())
{
cout << *vit << endl;
vit++;
}
}
void test_string4() //使用list可以直接插入数字
{
list<int> l;
l.push_back(6);
l.push_back(7);
l.push_back(8);
l.push_back(9);
list<int>::iterator lit = l.begin();
while (lit != l.end())
{
cout << *lit << endl;
lit++;
}
}
int strnum(const string& str) //传入一个对象,对对象里的字符串转换
{
int num = 0;
string::const_iterator it = str.cbegin();
while (it != str.cend())
{
num *= 10;
num += *it - '0';
++it;
}
return num;
}
int numstr(string& str)
{
int num = 0;
for (int i = 0; i<str.size(); i++)
{
num *= 10;
num += str[i] - '0';
}
return num;
}
int numstrey(string& str) //语法糖
{
int num = 0;
for (auto&e : str)
{
num *= 10;
num += e - '0';
}
return num;
}
void test_string5() //reserve,和resize
{
string s8("hahah");
cout << s8 << endl;
cout << s8.size()<< endl;
cout << s8.capacity() << endl;
s8.reserve(50);
cout << s8 << endl;
cout << s8.size() << endl;
cout << s8.capacity() << endl;
s8.resize(80,'1');
cout << s8 << endl;
cout << s8.size() << endl;
cout << s8.capacity() << endl;
string s9("i believe i can");
s9[10] = 'I';
cout << s9 << endl;
}
void test_string6() // push_back append erase atoi 的应用
{
string s1("hello");
s1.push_back(' ');
s1.append("world ");
cout << s1 << endl;
s1 += 'M';
s1 += "y name";
string s2("is");
s1 += s2;
s1.insert(s1.begin(), 'X');
s1.insert(0, "YZ");
s1.erase(0,3);
cout << s1 << endl;
string s3("111");
int ret=atoi(s3.c_str());
cout << s3 << endl;
}
void test_string7() // 去除文件后缀...
{
string file("test.cpp");
size_t pos = file.rfind('.');
if (pos == string::npos)
{
cout << "文件没有后缀" << endl;
}
else
{
cout << file.substr(pos, file.size() - pos) << endl;
}
string url("https://daohang.qq.com/?fr=hmpage");
size_t start = url.find("://");
if (start == string::npos)
{
cout << "url invalid" << endl;
return;
}
start += 3;
size_t finsh = url.find('/', start);
cout << url.substr(start, finsh - start) << endl;
pos = url.find("://");
url.erase(0, pos + 3);
cout << url << endl;
}
void test_string8()
{
string s1("hello");
string s2("world");
cout << s1 + s2 << endl;
cout << s1 + "world" << endl;
cout << "hello" + s2 << endl;
}