您的位置:首页 > 其它

string类成员函数的使用方法(一)

2016-04-12 15:07 435 查看
是一个类模板,里面包含了basic_string和char_straits两个类.

一.basic_string类

这个类的的typedef如下:

//窄字符
typedef basic_string<char, char_traits<char>, allocator<char> >
string;
//宽字符
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >
wstring;


它的成员变量和说明如下:

allocator_type 对象分配器

const_iterator 随机读写定位器,他能进入和读出string中的常量元素

const_pointer string的常量指针

const_reference 常量引用

const_reverse_iterator 随机读取string中的常值元素,从后面开始读

difference_type 在同一个string中两个迭代器的区别

iterator 随机的普通迭代器

npos 无符号整数,初始值为-1,当查找失败或者没有找到则返回-1

pointer 普通指针

reference 普通引用

reverse_iterator 随机读取string中的元素, 从后面开始读

size_type string对象中的元素个数

traits_type 提供一个traits

value_type 存储的数据类型

常用构造函数的用法:

窄字符版:

1.

string s("hello");//输出为hello


2.

string s("hello",2);//输出为he
//或者
char* p = "hello word";
string s(p,5); //输出为hello


3.

char* p = "hello word";
string s(p,2,5); //从第3个(0 1 2)开始输出5个字符


4.

string s(3,'A'); //输出三个A


5.

string s1("hello word");
//一对迭代器,输出结果为llo wo
string s2(s1.begin()+2,s1.end()-2);


6.

string s1("hello word");
string s2(s1);
string s3(s1 + " hello word");
string s4(s1 + s2 + s3);


宽字符版:

1.

wstring s(L"hello");//输出为hello
wcout << s << endl;


2.

wchar_t* p = L"hello word";
wstring s(p, 5); //输出为hello
wcout << s << endl;


3.

wchar_t* p = L"hello word";
wstring s(p, 2, 5); //从第3个(0 1 2)开始输出5个字符
wcout << s << endl;


4.

wstring s(3, 'A'); //输出三个A
wcout << s << endl;


5.

//下面三个都可以

//窄->宽
string s1("hello word");
wstring s2(s1.begin() + 2, s1.end() - 2);

//宽->宽
wstring s3(L"hello word");
wstring s4(s3.begin() + 2, s3.end() - 2);

//宽->窄
wstring s5(L"hello word");
string s6(s5.begin() + 2, s5.end() - 2);

wcout << s2 << endl;
wcout << s4 << endl;
cout << s6 << endl;


6.

wstring s1(L"hello word");
wstring s2(s1);
wstring s3(s1 + L" hello word");
wstring s4(s1 + s2 + s3);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: