今天用到了insert其中的一个用法 在指定位置插入一个char,结果用的时候和用法中在指定位置插入string用混了。所以打算整理一下insert的常见用法,也让自己记忆更深刻一点。
1,
//basic_string& insert( size_type index, size_type count, CharT ch );
//在字符串中第index个位置插入count个字符‘ch’
string str1 = “hello”;
string str2 = str1.insert(0,2,‘x’);//在str1中第0个位置插入2个字符‘x’
cout<<str2<<endl; //xxhello
2,
//basic_string& insert( size_type index, const basic_string& str );
//在字符串第index位置插入一个string
string str1 = “hello”;
string str2= str1.insert(1,str1);//在字符串str1第1个位置插入str1
cout<<str2<<endl; //hhelloello
//basic_string& insert( size_type index, const CharT s );
//在index位置插入一串字符*
string str1 = “hello”;
string str2= str1.insert(1,‘aaaa’);//在str1的第一个位置插入字符串‘aaaa’
cout<<str2<<endl; //haaaaello
3,
//basic_string& insert( size_type index, const CharT s, size_type count );
//在index位置插入字符串中的count个字符*
string str1 = “hello”;
string str2= str1.insert(1,“word”,2);//在str1的第一个位置插入字符串’word’中的2个字符wo
cout<<str2<<endl; //hwoello
4,
//basic_string& insert( size_type index, const basic_string& str,size_type index_str, size_type count );
//在index位置插入常量str的从index_str开始的count个字符
string str1 = “hellobeijing”;
string str2 = “helloword”;
string str3= str2.insert(6,str1,3,3);//在str2的第六个位置插入str1的从3开始的3个字符‘lob’
cout<<sstr<<endl; //hellowlobord
5,
//void insert( iterator pos, size_type count, CharT ch );
//在迭代器指向的pos位置插入count个字符ch
string str1 = “hello”;
str1.insert(++str1.begin(),2,‘a’);
//在迭代器指向str1++(即从0开始第一个位置)位置插入2个字符’a’
cout<<str1<<endl; //haaello
感觉常用的就这些吧。