string类也是常用的东西,很重要!
1. 七种构造函数
string (); //最简单的一种,无参构造函数
string (const char * s);
string (size_type n,char c);
string (const char * s,size_type n);
string (const string & str,size_tpye n=npos); //带默认值的
template<class Iter> string(Iter begin,Iter end); //使用迭代器的
string::npos (通常为最大unsigned int值,比最大索引大1) //常与find函数连用,判断find的结果
2、例子
//string_example.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string one("string construct !"); //string (const char * s);
cout << one << endl;
string two(20, '$'); //string (size_type n,char c);
cout << two << endl;
string three(one); //copy construct function
cout << three << endl;
one += " RYP_S!"; //append
cout << one << endl;
two = "hello world ! ";
three[0] = 'P'; //substitution
string four;
four = two + three; //join
cout << four << endl;
char alls[] = "stay hungry,stay foolish!";
string five(alls,20); // string (const char * s,size_type n);
cout << five << "!\n";
string six(alls+6, alls + 10); // template<class Iter> string(Iter begin,Iter end);
cout << six << ", ";
string seven(&five[6], &five[10]); // template<class Iter> string(Iter begin,Iter end);
cout << seven << "...\n"<<endl;
return 0;
}
运行结果如下: