1、二分法: //二分法:搜索已排序好的字符串组 #include<iostream> using namespace std; int bisearch(char** arr,int b,int e,char* v) { int minIndex=b,maxIndex=e,midIndex=0; while(minIndex < maxIndex) { midIndex = minIndex + (maxIndex-minIndex)/2; int flag = strcmp(arr[midIndex] , v); if( flag < 0) minIndex = midIndex; else if( flag == 0) return midIndex; else maxIndex = midIndex; } return -1; } int main() { char* arr[] = {"ahello","bthe","cworld","dthanks","eyou","fvery","gmuch","kgdk"}; int sz= sizeof(arr)/4; for(int i=0;i<sz;++i) cout<<bisearch(arr,0,sz,arr[i])<<endl; return 0; } 2、字符串转变成整数 //实现字符串转化成整数 //要求输入:“123445”,字符串里的字符是数字 #include<iostream> using namespace std; int atoi(const char* str) { int sz=0; int i=0; while(str[i] != '/0') { if(str[i]<48 || str[i]>57) return 0; ++sz;//统计字符串的长度(不包括'/0') ++i; } i=0; int integer=0; while(str[i] != '/0') { if(str[i]<48 || str[i]>57) return 0; else { int tempsize = sz-1; int bit =str[i]-48;//当前的位数 while(tempsize--) bit *= 10; --sz; integer+=bit; ++i; } } return integer; } int main() { char s[] = " 876543210"; int Integer = atoi(s); cout<<"convert s to integer is: "<<Integer<<endl; return 0; } 3、删除代码里的注释 //删除代码里的注释,注释以“//"大头,注释均位于单独的一行 #include<iostream> #include<fstream> #include<vector> #include<string> using namespace std; ofstream& delete_cpp_code_annotation(ifstream& in,ofstream& out) { string s; vector<string> svec; while(getline(in,s)) //把文件读入内存,存入vector<string>中 { // cout<<s<<endl; svec.push_back(s); } //删除注释 for(vector<string>::iterator it=svec.begin(); it<svec.end(); ++it) { if(*it == "" ) { out << "/n"; continue; } if(*it != "") { int i=0; for(i=0;i<(*it).length();++i) if((*it)[i] != ' ') break; if((*it)[i] != '/') out << *it << "/n"; } } return out; } int main(int argv1,char** argv2) { ofstream outfile; string out_file_name = "NewCUP.txt"; outfile.open(out_file_name.c_str()); if(outfile) cerr<<"OK"<<endl; ifstream infile; string input_file_name = "CUP.txt"; infile.open(input_file_name.c_str()); if(!infile) { cerr<<"error:unable to open file"<<endl; return -1; } delete_cpp_code_annotation(infile,outfile); outfile.close(); infile.close(); return 0; }