C++11:string类的常用接口说明及其功能测试
- string类对象的常见构造
- string类对象的容器操作
- string类对象的访问及其遍历操作
- string类对象的修改操作
测试代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
#include<functional>
using namespace std;
void fun(int n)
{
string str;
str.reserve(100);//一次性预留空间,提升效率,减少扩容次数
for (int i = 0; i < n; ++i)
{
cout << "capacity = " << str.capacity() << endl;
str.push_back('a');
}
}
int my_strlen(const char *str)
{
int count = 0;
while (*str++ != '\0')
{
count++;
}
return count;
}
int main()
{
//字符串构造
string str1;
cout << "str1 = " << str1 << endl;
string str2("zxcvbnm");
cout << "str2 = " << str2 << endl;
string str3(10, '#');
cout << "str3 = " << str3 << endl;
string str4(str3);
cout << "str4 = " << str4 << endl;
//功能测试
cout << "size = " << str3.size() << endl;//求有效字符长度
cout << "length = " << str3.length() << endl;//字符串特有计算有效字符长度
cout << "capacity = " << str3.capacity() << endl;//字符串容量
str3 += "sadasdasdasda";
cout << "capacity = " << str3.capacity() << endl;//自动扩容
str3.clear();
cout << "size = " << str3.size() << endl;
str2.resize(15, '+');//重新调整元素个数
cout << "str2 = " << str2 << endl;
cout << "length = " << str2.length() << endl;
cout << "capacity = " << str2.capacity() << endl;
str2.resize(3, '+');
cout << "str2 = " << str2 << endl;
str2.reserve(10);//调整预留容量
cout << "capacity = " << str2.capacity() << endl;
str2.reserve(100);
cout << "capacity = " << str2.capacity() << endl;
//fun(100);
for (unsigned int i = 0; i < str2.size(); ++i)
{
cout << str2[i];
}
cout << endl;
auto it = str2.begin();
while (it != str2.end())
{
cout << *it;
++it;
}
cout<<endl;
for (const auto &e : str2)
cout << e;
cout << endl;
auto rit = str2.rbegin();
while (rit != str2.rend())
{
cout << *rit;
++rit;
}
cout << endl;
str2.push_back('H');//在字符串后插入字符
str2.append("xht");//追加字符串
str2 += "mad";
cout << str2 << endl;
//C str 找到对象内部的指针将其类型强转为c类型的指针
cout << "str length = " << my_strlen(str2.c_str()) << endl;
string str = "https://blog.csdn.net/qq_42613519";
//size_t pos = str.find('b');
//size_t pos = str.find("net");
size_t pos = str.rfind('4');
if (pos != string::npos)
cout << "pos = " << pos << endl;
else
cout << "查找字符不存在" << endl;
size_t start_pos = str.find('b');
size_t end_pos = str.find('9');
cout << "pos = " << end_pos << endl;
string tmp_str = str.substr(start_pos, end_pos - start_pos + 1);//获取子串
cout << tmp_str << endl;
system("pause");
return 0;
}
测试结果(部分)