您的位置:首页 > 编程语言 > C语言/C++

string in C++98 的用法总结

2016-05-20 21:19 471 查看
写在前面
string对象是表示字符串的对象,支持单字符操作,还有一些很好的函数,方便了编程。为了很好地使用这个类,这里做一下用法总结。
string类是basic_string类模板的一个实例,它的字符类型是char。string对象支持单字节字符操作,不支持多字符编码或变长编码字符的处理。
谈到头文件的问题,string.h和cstring.h头文件支持对C-风格字符串进行操作的C库字符串函数。string类由头文件<string>支持。
用法总结
(1)构造函数
default (1)	string();
copy (2)	string (const string& str);
substring (3)	string (const string& str, size_t pos, size_t len = npos);
from c-string (4)	string (const char* s);
from sequence (5)	string (const char* s, size_t n);
fill (6)	string (size_t n, char c);
range (7)	template <class InputIterator> string  (InputIterator first, InputIterator last);
string str1 = "test compare fun!";
string str2 = "test d";
char chtest[] = "string test compare fun!";
char chtest1[10] = "test";
string strtest = "Telephone home.";

vector<char> input(6);
input[0] = 's',input[1] = 't',input[2] = 'r',input[3] = 'i';

cout << "str1:" << str1 << endl << endl;

cout << "str2:" <<str2 << endl << endl;

cout << "chtest:" << chtest << endl << endl;

cout<< "chtest1:" <<chtest1 << endl << endl;

cout<< "strtest:" <<strtest << endl << endl;

//string ctor function test

string str3(strtest);
cout << "str3(strtest) :"<< str3 << endl << endl;

string str4(strtest,4);
cout << "str4(strtest,4) :"<< str4 << endl << endl;

string str5(strtest,4,5);
cout << "str5(strtest,4,5) :"<< str5 << endl << endl;

string str6(6,'c');
cout << "str6(6,'c'):"<< str6 << endl << endl;

string str7(chtest+7,chtest+12);
cout << "str7(chtest+7,chtest+12):"<< str7 << endl << endl;

string str8(input.begin(),input.end());
cout << "str8(input.begin(),input.end()):"<< str8 << endl << endl;
(2)比较函数

string (1)	int compare (const string& str) const;
substrings (2)	int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,size_t subpos, size_t sublen) const;
c-string (3)	int compare (const char* s) const;
int compare (size_t pos, size_t len, const char* s) const;
buffer (4)	int compare (size_t pos, size_t len, const char* s, size_t n) const;


//string compare function test
//1 iAns should be -1
int iAns = str1.compare(str2);
cout << "1 str1.compare(str2):" << iAns << endl << endl;

//2 iAns should be -1
iAns = str1.compare(0,5,str2);
cout << "2 str1.compare(0,5,str2):" << iAns << endl << endl;

//3 iAns should be 0
iAns = str1.compare(0,5,str2,0,5);
cout << "3 str1.compare(0,5,str2,0,5):" << iAns << endl << endl;

//4 iAns should be 1
iAns = str1.compare(chtest);
cout << "4 str1.compare(chtest):" << iAns << endl << endl;

//5 iAns should be 0
iAns = str1.compare(0,4,chtest1);
cout << "5 str1.compare(0,4,chtest1):" << iAns << endl << endl;
(3)运行结果(codeblock + GUC)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: