常用字符串处理方法
读取文件中所有字符,包括空格。
1 #include <iostream> 2 #include <string> 3 #include <fstream> 4 #include <vector> 5 #include <algorithm> 6 7 using namespace std; 8 9 int main() 10 { 11 fstream in("d:\\demo.txt"); 12 in>>noskipws; 13 char c; 14 vector<int> words; 15 long records=0; 16 long word=0; 17 while(!in.eof()) 18 { 19 20 in >> c; 21 if(in.eof())break; 22 if(c == '\n')continue; 23 if(c == '.') 24 { 25 words.push_back(word); 26 word=0; 27 ++records; 28 continue; 29 } 30 ++word; 31 } 32 33 in.close(); 34 sort(words.begin(),words.end()); 35 return 0; 36 }
字符串分割的方法:
1 void split(string &str,char c,vector<string> &v) 2 { 3 string::iterator begin=str.begin(); 4 long pos1=0; 5 long pos2=0; 6 while(begin!=str.end()) 7 { 8 if(*begin == c) 9 { 10 string s = str.substr(pos1,pos2); 11 v.push_back(s); 12 pos1=pos2; 13 ++pos1; 14 } 15 ++pos2; 16 ++begin; 17 } 18 if(pos2>pos1) 19 { 20 string s = str.substr(pos1,pos2); 21 v.push_back(s); 22 } 23 }