1. String 与char*的区别:
- string是一个类,char是一个指针
string 封装了char,管理该字符串,是个char*的容器 - string封装了很多实用的方法
如:查找,拷贝,删除,替换,插入等 - string不需要考虑内存释放和越界问题
2. String和char*的转换:
string转char
string str = "deffre";
//注意:这里要加上 const,否则会有编译警告;
const char* cstr = str.c_str();
char* 转string
直接赋值
char* = “ssss”;
string sstr(s);
3.string拼接
4.string 查找和替换
5.string插入和删除
6.string子串操作
返回由pos开始的n个字符串组成的新字符串
string substr(int pos =0, int n = npos) const;
7.代码测试
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string>
using namespace std;
//初始化
void test01(){
string s1; //调用无参构造
string s2(10, 'a');
string s3("abcdefg");
string s4(s3); //拷贝构造
cout << "********* string init *********";
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << endl;
}
//赋值操作
void test02(){
string s1;
string s2("appp");
s1 = "abcdef";
cout <<endl<< "********* string copy *********"<<endl;
cout << s1 << endl;
s1 = s2;
cout << s1 << endl;
s1 = 'a';
cout << s1 << endl;
//成员方法assign
s1.assign("jkl");
cout << s1 << endl;
}
//取值操作
void test03(){
cout << endl << "********* string [] *********" << endl;
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_range
try{
//cout << s1[100] << endl;
cout << s1.at(100) << endl;
}
//能够捕获任何异常的 catch 语句
catch (...){
cout << "越界!" << endl;
}
}
//拼接操作
void test04(){
string s = "abcd";
string s2 = "1111";
s += "abcd";
s += s2;
cout << endl << "********* string append *********" << endl;
cout << "s = " << s << endl;
//append 会加到尾部
string s3 = "2222";
s2.append(s3);
cout <<"s2 = "<< s2 << endl;
string s4 = s2 + s3;
cout << "s4 = "<< s4 << endl;
}
//查找操作
void test05(){
string s = "abcdefghjfgkl";
//查找第一次出现的位置
int pos = s.find("fg");
cout << endl << "********* string find *********" << endl;
cout << "pos:" << pos << endl;
//查找最后一次出现的位置
pos = s.rfind("fg");
cout << "pos:" << pos << endl;
}
//string替换
void test06(){
string s = "abcdefg";
s.replace(3,2,"111");
cout << endl << "********* string replace *********" << endl;
cout << "string replace test: " << s << endl;
}
//string比较
void test07(){
string s1 = "abcd";
string s2 = "abce";
cout << endl << "********* string compare *********" << endl;
if (s1.compare(s2) == 0){
cout << "字符串相等!" << endl;
}
else{
cout << "字符串不相等!" << endl;
}
}
//子串操作
void test08(){
string s = "abcdefg";
string mysubstr = s.substr(1, 7);
cout << endl << "********* string substr *********" << endl;
cout << mysubstr << endl;
}
//插入和删除
void test09(){
cout << endl << "********* string insert and delete *********" << endl;
string s = "abcdefg";
s.insert(3,"222");
cout << s << endl;
string ss = "kkk";
s.insert(3, ss);
cout << s << endl;
s.erase(0, 2);
cout << s << endl;
}
int main(void){
test01();
test02();
test03();
test04();
test05();
test06();
test07();
test08();
test09();
return 0;
}
程序运行结果: