- C 没有 string 类,但提供了直接对字符数组、字符串操作的函数 -> 如 str_len()等等 -> 需要包含 “string.h”
#include<iostream>
#include<string>
using namespace std;//初始化
void test01() {string s1; //调用无参构造string s2(10, 'a');string s3("abcdefg");string s4(s3); //拷贝构造cout << s1 << endl;cout << s2 << endl;cout << s3 << endl;cout << s4 << endl;
}
/*
输出为:aaaaaaaaaa
abcdefg
abcdefg
*///赋值操作
void test02() {string s1;string s2("appp");s1 = "abcdefg";cout << s1 << endl;s1 = s2;cout << s1 << endl;s1 = 'a';cout << s1 << endl;s1.assign("jkl"); //成员方法cout << s1 << endl;
}
/*
输出为:
abcdefg
appp
a
jkl
*///取值操作
void test03()
{string s1 = "abcdefg";//重载[]操作符for (int i = 0; i < s1.size(); i++){cout << s1[i] << " ";}cout << endl;//at成员函数for (int i = 0; i < s1.size(); i++){cout << s1.at(i) << " ";}cout << endl;//区别:[]访问越界 直接挂了// at方式越界,抛异常 out_of_rangetry {cout << s1.at(100) << endl; //程序不会挂掉,因为at会抛异常//cout << s1[100] << endl; //程序挂掉,因为[]不会抛异常}catch (...) {cout << "越界!" << endl;}
}
/*
输出为:
a b c d e f g
a b c d e f g
越界!
*///拼接操作
void test04()
{string s = "1234545";string s2 = "111";s += "abbbb";s += s2;cout << s << endl;string s3 = "3333";s2.append(s3); //将s3追加到s2的尾部cout << s2 << endl;string s4 = s2 + s3;cout << s4 << endl;
}
/*
输出为:
1234545abbbb111
1113333
11133333333
*///查找操作
void test05() {string s = "abecasdgdgdg";//查找第一次出现的位置int pos=s.find("dg");cout << "pos:" << pos << endl;int rpos = s.rfind("dg");cout << "rpos:" << rpos << endl;
}
/*
输出为:
pos:6
rpos:10
*///替换操作
void test06() {string s = "abcdefg";//替换从pos开始n个字符为字符串str s.replace(pos,n,str)s.replace(0, 2, "111");cout << s << endl;
}
/*
输出为:
111cdefg
*///比较操作
void test07() {//比较区分大小写,比较时参考字典顺序,排越前越小string s1 = "abcd";string s2 = "abcde";if (s1.compare(s2) == 0)cout << "字符串相等!" << endl;elsecout << "不相等" << endl;}
/*
输出为:
不相等
*///子串操作
void test08() {string s1 = "abcd";//将位置1到位置3的字符串截取string s2=s1.substr(1, 3);cout << s1 << endl;cout << s2 << endl;
}
/*
输出为:
abcd
bcd
*///插入和删除操作
void test09() {string s1 = "abcdefg";s1.insert(3, "1212");cout << s1 << endl;s1.erase(0, 2);cout << s1 << endl;
}
/*
输出为:
abc1212defg
c1212defg
*/int main()
{cout << "-------------test01----------" << endl;test01();cout << "-------------test02----------" << endl;test02();cout << "-------------test03----------" << endl;test03();cout << "-------------test04----------" << endl;test04();cout << "-------------test05----------" << endl;test05();cout << "-------------test06----------" << endl;test06();cout << "-------------test07----------" << endl;test07();cout << "-------------test08----------" << endl;test08();cout << "-------------test09----------" << endl;test09();return 0;
}
参考自https://blog.csdn.net/dark_cy/article/details/84791900