string

string对象的定义和初始化

示例代码:

#include <string>
#include <iostream>

using namespace std;

void fun(char *str)
{
        cout << str << endl;
}

int main(void)
{
        string s1("abcdefdg");
        cout << s1.size() << endl;
        cout << s1.length() << endl;
        cout << s1.empty() << endl;

        cout << s1.substr(1,2) << endl;//npos=-1,
        cout << s1.substr(1) << endl;//npos=-1,<=>s1.substr(1,-1)<=>s1.substr(1,string::npos)

        string::size_type pos = s1.find('d',1);//find char or string
        if (pos == string::npos)
                cout << "not found" << endl;
        else
                cout << "pos = " << pos << endl;

        pos = s1.rfind('d',7);//rfind char or string
        if (pos == string::npos)
                cout << "not found" << endl;
        else
                cout << "pos = " << pos << endl;

        s1.replace(2,2,"ABCDEF");
        cout << s1 << endl;

        fun(const_cast<char*>(s1.c_str()));//c_str()change string to char *



        return 0;
}

 

posted on 2017-11-14 00:00  Malphite  阅读(90)  评论(0编辑  收藏  举报