C++定义了一个内容丰富的抽象数据类型标准库。
string初始化:2没用过的方法
- string s("hello");
- 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
- string s;
- while (cin>>s) //while(getline(cin, s))
- {
- cout<<s<<endl;
- }
习题3.7
- ifstream f1("text.txt");
- string s1;
- string s2;
- getline(f1, s1);
- getline(f1, s2);
- if (s1 == s2)
- cout<<"equal!"<<endl;
- else if (s1 > s2)
- cout<<s1<<" is bigger"<<endl;
- else
- cout<<s2<<" is bigger"<<endl;
- f1.close();
- ifstream f1("text.txt");
- string s1;
- string s2;
- getline(f1, s1);
- getline(f1, s2);
- if (s1.size() == s2.size())
- cout<<"equal!"<<endl;
- else if (s1.size() > s2.size())
- cout<<s1<<" is bigger"<<endl;
- else
- cout<<s2<<" is bigger"<<endl;
- f1.close();
习题3.8
- ifstream f1("text.txt");
- string s1;
- string s2;
- getline(f1, s1);
- getline(f1, s2);
- s1 = s1 + " " + s2;
- cout<<s1<<endl;
- f1.close();
习题3.10
- ifstream f1("text.txt");
- string s1;
- string s2;
- getline(f1, s1);
- typedef string::size_type string_sz;
- for (string_sz i = 0; i != s1.size(); i++)
- {
- if (!ispunct(s1[i]))
- s2.push_back(s1[i]);
- }
- cout<<s2<<endl;
- f1.close();
习题3.13
- ifstream f1("text.txt");
- vector<int> vec;
- vector<int> vec2;
- typedef vector<int>::size_type vec_sz;
- int n;
- while (f1>>n)
- {
- vec.push_back(n);
- }
- vec_sz i ;
- for (i= 0; i != vec.size() - 1; i += 2)
- {
- vec2.push_back(vec[i] + vec[i+1]);
- }
- if (vec.size()%2 != 0)
- {
- cout<<"奇数"<<vec[i];
- }
- f1.close();
习题3.14
- ifstream f1("text.txt");
- vector<string> str;
- typedef vector<string>::size_type vec_sz;
- typedef string::size_type string_sz;
- string s;
- vec_sz i = 0;
- while (f1>>s)
- {
- str.push_back(s);
- for(string_sz j = 0; j != str[i].size(); ++j)
- {
- if (islower(str[i][j]))
- str[i][j] = toupper(str[i][j]);
- }
- cout<<str[i]<<endl;
- i++;
- }
- f1.close();