string类的七种构造函数

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;
}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值