#include <iostream>
#include <string>
using namespace std;
//初始化-----------------------------------------------------
void test01() {
string a;//默认构造函数
string b("string");
string c = "java";
string d(b);//拷贝构造
if (a == "")
cout << "a==\"\"";//string a;将a初始化为 ""
a = b + c;//将c加载b的尾部再赋值给a;
b.append(c);//在b尾部直接加上c
if (a == b&&d == b)
cout << "a == b" << endl;
}
//读取某个位置元素------------------------------------------
void test02()
{
string a("dasda");
try
{
//[]不提供异常机制 .at()提供异常机制
cout << a.at(222);
}
catch (...)
{
cout << "越界啦!" ;
}
}
//string 中find rfind函数--------------------------------
void test03() {
string a;
a.append("asdfgas");
//从头往后找
int i = a.find("as");
cout << i << " ";
//从尾部往前找
i = a.rfind("as");
cout << i << " ";
//失败返回-1
i = a.find("ad");
cout << i;
}
//求字符串长度-----------------------------------------
void test04() {
string s;
string a("string");
s = s + a;
cout << "length= " << s.size() << " " << s.length();
}
//比较字符串大小----------------------------
void test05() {
string a = "hefei";
string b = "anhui";
string c = "anhui";
cout<<a.compare(b)<<" "<<b.compare(a)<<" "<<b.compare(c);//输出1 -1 0 a.cmp(b) a>b 返回1 依次类推
}
//字符串在某个位置插入另一字符串-------------------------------
void test06() {
string a("mystring");
string b = "c++";
a.insert(1,"c++");// == a.insert(1,b),表示在第0个位置前插入 此时a=mc++ystring
//a.insert(30, b); //error 因为30>a.size()
a.insert(a.length(), b); // == a.size() 此时a=mc++ystringc++
cout << a ;
}
//字符串的删除--------------------------------------------
void test07() {
string a("c++ is difficult!");
a.erase(6);//删除a.at(6)及之后所有元素
cout << a << endl;
a.erase(3, 2);//从第a.at(3)开始连续删除2个元素
cout <<a.length()<<" "<<a ;
}
//字符串的替换-------------------------------------
void test08() {
string a = "learning c++";
a.replace(3, 2, "int");//将a.at(3)开始的两个元素替换为int
cout << a;
}
//迭代器------------------------------------
void test09() {
string a = "c++ is interesting!";
for (string::iterator it = a.begin(); it != a.end();it++) {
cout << *it;
}
}
int main()
{
test01();
cout<<endl << "--------------------- -----------------------"<<endl;
test02();
cout << endl << "--------------------------------------------" << endl;
test03();
cout << endl << "--------------------------------------------" << endl;
test04();
cout << endl << "--------------------------------------------" << endl;
test05();
cout << endl << "--------------------------------------------" << endl;
test06();
cout << endl << "--------------------------------------------" << endl;
test07();
cout << endl << "--------------------------------------------" << endl;
test08();
cout << endl << "--------------------------------------------" << endl;
test09();
cout << endl << "--------------------------------------------" << endl;
return 0;
}
C++string 基本函数实现
猜你喜欢
转载自blog.csdn.net/qq_42673507/article/details/84962691
今日推荐
周排行