c++教程:string类型

2025-10-10 10:29:36

1、string 对象的初始化:下面的写法都是合法的。

string a = "hello world";

string *b = new string("hello world");

const char* str = "this is const str";

string c = str;

string *d = new string(str);

string e(10,'a'); // 这个不常用

string f(str);

c++教程:string类型

2、两个字符串可以方便的“+”在一起:

string a = "hello ";

string b = a + "world";

cout << b << endl;

c++教程:string类型

3、string同样支持+=操作符:

string a = "you name:";

a +=" cpp";

a += string(" good");

cout << a << endl;

c++教程:string类型

4、可以用==进行字符串比较:

        const string a = "test";

        const string b = "test";

        const string c = "testc";

        if(a  == b)

        {

                cout << "Match ok" << endl;

        }

        if(a  == c)

        {

                cout << "Match ok !" << endl;

        }

        return 0;

c++教程:string类型

5、string和 const char* 类型的转换:只是初学者经常遇到的问题

        string a = "hello";

        const char* b = a.c_str();

        char* c  = "hello";

        string d(c);

        const char* e = const_cast<char*>(c);

c++教程:string类型

6、字符串查找的方法有find、find_first_of,find_first_not_of等方法。

        string a = "hello world";

        cout << a.find("world") << endl;

        cout << a.find_first_of("world") << endl;

        cout << a.find_first_not_of("world") << endl;

        return 0;

c++教程:string类型

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢