这是第一部分。
和其他博客一样,我还是采用代码方式描述,引入,具体细节请查询文档或根据代码推测,编译运行。
- 赋值
- 数据处理
- 迭代,遍历
- 一些常用辅助性函数
#include<iostream>
#include<string>
using namespace std;
int main(){
string str = "str";
str.push_back('i');
cout<<str.size()<<" "<<str.length()<<" "<<str.max_size()<<endl;
for(string::iterator iter = str.begin() ; iter != str.end();iter++)
cout<<(*iter);
cout<<endl;
bool empty = true;
empty = str.empty();
cout <<"that str is empty is "<<boolalpha<<empty<<endl;
}
//添加库string
//使用push_back来增加元素
//使用size或length得出string的长度
//使用迭代器来进行简易的输出
//使用empty()函数判断是否非空
#include<iostream>
#include<string>
using namespace std;
int main(){
//part1 赋值
string str1 = "RALPHFJY";
string str2 = "FUNKYA";
str1 = str2;
cout<<str1;
cout<<endl;
str1.assign("RALPHFJY LOVE FUNKTA");
cout<<str1;
cout<<endl;
str1.assign("RALPHFJY LOVE FUNKYA",9,4); //begin and number
cout<<str1<<endl;
str1.assign("RALPHFJY LOVE FUNKTA",14);
cout<<str1<<endl;
char temp[] ="we are together";
str1.assign(temp);
cout<<str1<<endl;
str1.assign(temp,2);
cout<<str1<<endl;
str1.assign(temp,0,2);
cout<<str1<<endl;
string ptr;
ptr.assign(5,'!'); //赋值
cout<<ptr<<endl;
}
}
//由上可见一些典型的string类赋值方法
//
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
string str = "RALPHFJY";
for(int index = 0 ; index <str.size();index++)
cout<<str.at(index);
cout<<endl;
cout<<str.front()<<endl;
cout<<str.back()<<endl;
const char *ptr = str.data();
cout<<(*ptr)<<endl;
cout<<str.c_str()<<endl; //returns a non-modifiable standard C character array version of the string
for(string::iterator iter = str.begin() ; iter != str.end() ; iter++)
cout<<(*iter);
cout<<endl;
for(string::const_iterator iter = str.cbegin() ; iter != str.cend() ; iter++)
cout<<(*iter);
cout<<endl;
/*for(string::iterator iter = str.rbegin() ; iter != str.rend() ; iter++)
cout<<(*iter);
cout<<endl; */
reverse(str.begin(),str.end());
cout<<str<<endl;
str.clear();
cout<<str<<endl;
cout<<"finished"<<endl;
}
//使用迭代器等方法进行遍历
//使用reverse
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
str.push_back('1');
str.pop_back();
cout<<"finished"<<endl;
cout<<str<<endl;
str.push_back('1');
str.push_back('2');
cout<<str<<endl;
str.insert(1,1,'3');
cout<<str<<endl;
str.assign("12");
str.insert(1,2,'3'); //index ,copy number,character
cout<<str<<endl;
str.assign("abcdefg");
str.erase(0,2);
cout<<str<<endl;
str.assign("abcdefg");
str.erase(2,4);
cout<<str<<endl;
string::iterator it = str.begin()+1 ;
str.assign("abcdefg");
str.erase(it);
cout<<str<<endl;
str.assign("abcdefg");
str.append();
cout<<str<<endl;
}
//一些数据操作