多语言展示
当前在线:1711今日阅读:168今日分享:49

c++教程:string类型

string并不是cpp的基本数据类型。string是c++标准库实现的类。
工具/原料
1

g++

2

centos 6.4

3

vim

方法/步骤
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);

2

两个字符串可以方便的“+”在一起:string a = 'hello ';string b = a + 'world';cout << b << endl;

3

string同样支持+=操作符:string a = 'you name:';a +=' cpp';a += string(' good');cout << a << endl;

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;

5

string和 const char* 类型的转换:只是初学者经常遇到的问题        string a = 'hello';        const char* b = a.c_str();        char* c  = 'hello';        string d(c);        const char* e = const_cast(c);

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;

注意事项

有不明白的给我留言

推荐信息