C++字符串常用函数示例
#include<iostream>
#include<string>
using namespace std;
void string_test(){
cout<<"C++常用字符串函数"<<endl;
cout<<"1.字符串替换"<<endl;
string father="0123456789abcdefg";
string temp = father.replace(0,10,"Hello World!");
cout<<temp<<endl;
// 输出:Hello World!abcdefg
father="012345678";
string child = "0123ABCDEF";
temp = father.replace(0,5,child,3,4);
// child中3ABC替换father的01234
cout << temp << endl<<endl;
// 输出:3ABC5678
cout<<"2.字符串追加"<<endl;
father="012345678";
child = "abcd";
father.append(child);
cout<<father<<endl;
// 输出:01234578abcd
// 追加 5 个指定字符
father.append(5,'!');
cout<<father<<endl;
// 输出:012345789!!!!!
child="abcxyz";
// 追加子串 pos=3,len=3
father.append(child,3,3);
cout<<father<<endl;
// 输出:012345678abcd!!!!!xyz
// 追加子串部分 pos=0;len=3;
father.append("ABCDEF",3);
cout<<father<<endl;
// 输出:012345678abcd!!!!!xyzABC
// 追加单个字符,这是错误的:father.append('W');
father.push_back('W');
cout<<father<<endl<<endl;
// 输出:012345678abcd!!!!!xyzABCW
cout<<"3.字符串拼接数字"<<endl;
int x = 100;
char ch[10];
sprintf(ch,"ABCD%d",x);
cout<<ch<<endl;
// 输出:ABCD100
// char * 转换为 string
string chstr = ch;
cout<<chstr<<endl<<endl;
// 输出:ABCD100
cout<<"4.字符串查找"<<endl;
father = "01234567";
int pos = father.find("67");
// int pos = father.find_first_of("67");
// int pos = father.find_last_of("67");
cout<<pos<<endl<<endl;
// 输出:6
cout<<"5.字符串截取"<<endl;
father = "012AABB";
// 从 father[3]开始截取 5 位
temp = father.substr(3,5);
cout<<temp<<endl<<endl;
// 输出:AABB
cout<<"6.字符串删除"<<endl;
father = "0123ABCD";
father.erase(2,3);
// 删除:23A
cout<<father<<endl;
// 输出:01BCD
father.erase(1);
// 删除father[1]及之后的所有字符 :1BCD
cout<<father<<endl<<endl;
// 输出:0
cout<<"7.字符串插入"<<endl;
father="012345";
father.insert(1,"!!!");
cout<<father<<endl<<endl;
// 输出:0!!!12345
// 字符串
cout<<"8.字符串其他属性"<<endl;
father="";
cout<<father.empty()<<endl;
// 输出:1
cout<<father.max_size()<<endl;
// 输出:4611686018427387897
father="Hello";
cout<<father.size()<<endl;
// 输出:5
cout<<father.length()<<endl;
// 输出:5
}
int main(){
string_test();
return 0;
}