/* * std::string深入詳解 * Visual Studio 2008Sp1, 使用Ctrl + F5啟動調試 */#include <iostream>#include <string>#include <cstdio>#include <cstddef>#include <cstring>#include <cstdlib> //qsort#include <errno.h>/* Error Codes */#include <numeric>#include <algorithm>using namespace std;//#define _CRT_SECURE_NO_WARNINGS with /D#pragma warning(disable:4996) //disable stupid warning of This function or variable may be unsafe. //Consider using strerror_s instead#define MAXLEN 1000char line[MAXLEN];int getline(char s[], int lim){int ch = 0, i;i = 0;while(--lim > 0 && ((ch = getchar()) != EOF) && ch != '\n')s[i++] = ch;if (ch =='\n')s[i++] = ch;s[i] = '\0';return i;}//raiseint cmp(const void *a, const void *b){return *(char *)b - *(char *)a;}int main(int argc, char *argv[]){const basic_string<char> s1("test something");string s2("test");// The first member function C-stringstring stra("hello ");const char *cstra = "c-string";stra.append(cstra);cout<<"Appending the C-string cstra to string stra gives: "<<stra<<endl<<endl;//// The second member functionconst char *cstrb = "some elsd";stra.append(cstrb,2);cout<<stra<<endl<<endl;cout<<"input a character string"<<endl;if(getline(line, MAXLEN) < 1)exit(1);//quick sortcout<<"before line: "<<line<<endl;qsort(line, sizeof(line)/sizeof(line[0]), sizeof(line[0]), cmp);cout<<"quick sort line: "<<line<<endl;///string 測試cout<<"測試string ss,下面給出ss的字串:"<<endl<<endl;string ss(" maybe you are long long girl, i'm who are you.12563.");cout<<ss<<endl<<endl;cout<<ss.find_first_not_of(' ')<<endl; //前面有很多空格,尋找第一個非空格的cout<<ss.find_first_not_of("abcdefghijkmno")<<endl; //返回第一個不在指定字元集裡面的元素位置cout<<ss.find_last_not_of("abcdefghijkmno")<<endl;cout<<ss.find("longk")<<endl; //如果string中沒有尋找的內容,他會超出範圍的去尋找cout<<"計算string ss中的 o 個數:"<<count(ss.begin(), ss.end(), 'o')<<endl;cout<<"string ss的長度: "<<ss.size()<<", string ss中的字母和數字: "<<count_if(ss.begin(), ss.end(), isalnum)<<endl; //條件比較,ctype.h isalnum判斷字母或者是數字////////////////////////////////////////////////////////////////////////////strcspn && strspncout<<endl<<endl<<endl;const char *pszTest = "long long ago, there is girl, she\'name is little redhat";cout<<"\r\n測試strcspn()函數,待測試的字串pszTest: "<<pszTest<<endl;cout<<"長度:"<<strlen(pszTest)<<"---firt_not_of length `xyza` "<<strcspn(pszTest, "xyza")<<endl;////////////////////////////////////////////////////////////////////////////test strtokchar str[] = "now#is the time for all#####good men to come to the#aid of their country\0";char *delims = "#";char *token = NULL;cout<<"\n\n測試strtok函數(linux下請使用函數·char *strsep (char ** __stringp, const char * __delim)·),""待測試的字串:\n"<<str<<endl<<endl;token = strtok(str, delims);//線程不安全的函數, 列外str被破壞掉了while(token != NULL){printf("%s\n", token);token = strtok(NULL, delims);}////////////////////////////////////////////////////////////////////////////memchrcout<<"\n\n\n測試函數void * memchr (void * ptr, int value, size_t num );\r\n"<<endl;char *pch;int ch;ch = 'e';strcpy(str, "now#is the time for all#####good men to come to the#aid of their country" );cout<<"The test str:\n"<<str<<endl;pch = (char *)memchr(str, ch, strlen(str));if (pch != NULL){printf(">>Character \'%c\' is found at %d.\n", ch, pch - str +1);printf(">>%s\n", pch);}else{printf("Fuck, Character \'%c\' is NOT found!\n", ch);}cout<<"\n\n"<<endl;////////////////////////////////////////////////////////////////////////////strerrorcout<<"測試strerror(),創造一個error: press any key continue..."<<endl;cin.get();//for(int err = 1; err < 42; err++){//printf("Error code%d: %s\n", err, strerror(err)); //}FILE *file;file = fopen("unexist.file", "r");if(file == NULL) printf("Open file crashed, Error code %d: %s\n", errno, strerror(errno));/////////////////////////////////////////////////////////////////////////////strcasecmpcout<<"\n\n測試strcasecmp()函數,輸入一隻動物吧!(dog,cat,etc...)"<<endl;/*使用自己的C函數*/if(getline(line, MAXLEN) >1){line[strlen(line) - 1] = '\0';//delete new line/* do something compare */if (stricmp(line, "dog") == 0){ //stricmp實質是引用了string.h中的strcasecmp()函數,坑爹啊printf("Dog is very interesting....en?\n");}else if (stricmp(line, "cat") == 0){printf("Actually, I do not like cats.\n");}else if(stricmp(line, "cow") == 0){printf("Cattle (colloquially cows) are the most common type of large domesticated ungulates." "They are a prominent modern member of the subfamily Bovinae, are the most widespread " "species of the genus Bos, and are most commonly classified collectively as Bos primigenius." " Cattle are raised as livestock for meat (beef and veal), as dairy animals for milk and " "other dairy products, and as draft animals (oxen / bullocks) (pulling carts, plows and " "the like). Other products include leather and dung for manure or fuel. In some countries, " "such as India, cattle are sacred. From as few as eighty progenitors domesticated in " "southeast Turkey about 10,500 years ago, it is estimated that there are now 1.3 billion " "cattle in the world today.\n");}else if (stricmp(line, "pig") == 0){printf("A pig is any of the animals in the genus Sus, within the Suidae family of even-toed ""ungulates. Pigs include the domestic pig, its ancestor the wild boar, and several other ""wild relatives. Pigs are omnivores and are highly social and intelligent animals.\n");}else{printf("%s ,?what animal it was??\n", line);}}//使用istream對象, std::string convert to C-style stringcout<<"輸入一些什麼東西吧\n"<<endl;std::string szline;std::getline(std::cin, szline); //don't be std::cinstrcpy(line, szline.c_str());printf(">>%s\n", line);/////////////////////////////////////////下面看看一個typedef與const的結合typedef std::string *pstring;//const pstring mystring;//error, 因為mystring變數是const類型的,先要初始化//const int jj;//errorstd::string mystr1("got some string here.");std::string mystr2("wow,i got the second string.");const pstring mystring = &mystr1;//mystring = &mystr2;//error 指標mystring只是指向mystr1的cout<<"mystring: \n"<<*mystring<<endl;mystring->append(" some append string.");cout<<"after append of mystring:\n"<<*mystring<<endl;return 0;}
輸出結果
Appending the C-string cstra to string stra gives: hello c-stringhello c-stringsoinput a character stringlong long ago, there is girl, she's name is little redhat..before line: long long ago, there is girl, she's name is little redhat..quick sort line: ttttssssrrrooonnnmllllliiiihhhggggeeeeeedaaa..,,'測試string ss,下面給出ss的字串: maybe you are long long girl, i'm who are you.12563.40554294967295計算string ss中的 o 個數:5string ss的長度: 56, string ss中的字母和數字: 39測試strcspn()函數,待測試的字串pszTest: long long ago, there is girl, she'name is little redhat長度:55---firt_not_of length `xyza` 10測試strtok函數(linux下請使用函數·char *strsep (char ** __stringp, const char * __delim)·),待測試的字串:now#is the time for all#####good men to come to the#aid of their countrynowis the time for allgood men to come to theaid of their country測試函數void * memchr (void * ptr, int value, size_t num );The test str:now#is the time for all#####good men to come to the#aid of their country>>Character 'e' is found at 10.>>e time for all#####good men to come to the#aid of their country測試strerror(),創造一個error: press any key continue...Open file crashed, Error code 2: No such file or directory測試strcasecmp()函數,輸入一隻動物吧!(dog,cat,etc...)pigA pig is any of the animals in the genus Sus, within the Suidae family of even-toed ungulates. Pigs include the domestic pig, its ancestor the wild boar, and several other wild relatives. Pigs are omnivores and are highly social and intelligent animals.輸入一些什麼東西吧lol.file>>lol.filemystring:got some string here.after append of mystring:got some string here. some append string.請按任意鍵繼續. . .