string类的构造函数

时间:2021-11-28 19:28:29

string (const char * s);   将string对象初始化为s指向的NBTS
string (size_type n,char c);   创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
string (const char * s,size_type n);  将string对象初始化为s指向的前n个字符,即使超过了NBTS的结尾
string (const string & str,size_tpye n=npos);  将string对象初始化为对象str中从位置pos开始到结尾的字符,或从位置pos开始的n个字符
string (); 创建一个默认的string对象,长度为0
template<class Iter>
string(Iter begin,Iter end);  将string对象初始化为区间[begin,end)内的字符,其中begin,end的行为就像指针,用于指定位置,范围包括begin在内,但是不包括end

string::npos  (通常为最大unsigned int值 比最大索引大1)

 

 

////////////////////////////////////////////
//
//string1.cpp
//
////////////////////////////////////////////
#include <iostream>
#include <string>
// using string constructors

int main()
{
    using namespace std;
    string one("Lottery Winner!");    // ctor #1
    cout << one << endl;              // overloaded <<
    string two(20, '$');              // ctor #2
    cout << two << endl;
    string three(one);                // ctor #3
    cout << three << endl;
    one += " Oops!";                  // overloaded +=
    cout << one << endl;
    two = "Sorry! That was ";
    three[0] = 'P';
    string four;                      // ctor #4
    four = two + three;               // overloaded +, =
    cout << four << endl;
    char alls[] = "All's well that ends well";
    string five(alls,20);             // ctor #5
    cout << five << "!\n";
    string six(alls+6, alls + 10);    // ctor #6
    cout << six  << ", ";
    string seven(&five[6], &five[10]);// ctor #6 again
    cout << seven << "...\n";

    return 0; 
}