C++定义了一个内容丰富的抽象数据类型标准库。

string初始化:2没用过的方法

  1. string s("hello"); 
  2. string s(5, 'a'); 

string::size_type类型

为string类类型的配套类型(companion type)。通过配套类型可以做到库类型使用和机器无关(machine-independent)。

string对象可以和字符串字面值混合连接。

string对象获取字符使用size_type类型下标(索引)。

字符操作函数,位于cctype中:

isalnum(c)

isalpha,isdigit,islower,ispunct,isspace,isupper,tolower,toupper

标准库vector类型

vector是同一种类型对象的集合,每个对象都有整数索引。

 

习题3.5

  1. string s; 
  2. while (cin>>s) //while(getline(cin, s))
  3.     cout<<s<<endl; 

习题3.7

  1. ifstream f1("text.txt"); 
  2. string s1; 
  3. string s2; 
  4. getline(f1, s1); 
  5. getline(f1, s2); 
  6. if (s1 == s2) 
  7.     cout<<"equal!"<<endl; 
  8. else if (s1 > s2) 
  9.     cout<<s1<<" is bigger"<<endl; 
  10. else 
  11.     cout<<s2<<" is bigger"<<endl; 
  12. f1.close(); 

  1. ifstream f1("text.txt"); 
  2.     string s1; 
  3.     string s2; 
  4.     getline(f1, s1); 
  5.     getline(f1, s2); 
  6.     if (s1.size() == s2.size()) 
  7.         cout<<"equal!"<<endl; 
  8.     else if (s1.size() > s2.size()) 
  9.         cout<<s1<<" is bigger"<<endl; 
  10.     else 
  11.         cout<<s2<<" is bigger"<<endl; 
  12.     f1.close(); 

习题3.8

  1. ifstream f1("text.txt"); 
  2. string s1; 
  3. string s2; 
  4. getline(f1, s1); 
  5. getline(f1, s2); 
  6. s1 = s1 + " " + s2; 
  7. cout<<s1<<endl; 
  8. f1.close(); 

习题3.10

  1. ifstream f1("text.txt"); 
  2. string s1; 
  3. string s2; 
  4. getline(f1, s1); 
  5. typedef string::size_type string_sz; 
  6. for (string_sz i = 0; i != s1.size(); i++) 
  7.     if (!ispunct(s1[i])) 
  8.         s2.push_back(s1[i]); 
  9. cout<<s2<<endl; 
  10. f1.close(); 

习题3.13

  1. ifstream f1("text.txt"); 
  2. vector<int> vec; 
  3. vector<int> vec2; 
  4. typedef vector<int>::size_type vec_sz; 
  5. int n; 
  6. while (f1>>n) 
  7.     vec.push_back(n); 
  8. vec_sz i ; 
  9. for (i= 0; i != vec.size() - 1; i += 2) 
  10.     vec2.push_back(vec[i] + vec[i+1]); 
  11.  
  12. if (vec.size()%2 != 0) 
  13.     cout<<"奇数"<<vec[i]; 
  14. f1.close(); 

习题3.14

  1. ifstream f1("text.txt"); 
  2. vector<string> str; 
  3. typedef vector<string>::size_type vec_sz; 
  4. typedef string::size_type string_sz; 
  5. string s; 
  6. vec_sz i = 0; 
  7. while (f1>>s) 
  8.     str.push_back(s); 
  9.     for(string_sz j = 0; j != str[i].size(); ++j) 
  10.     { 
  11.         if (islower(str[i][j])) 
  12.             str[i][j] = toupper(str[i][j]); 
  13.     } 
  14.     cout<<str[i]<<endl; 
  15.     i++; 
  16. f1.close();