C++中的字符串操作:
字符串的输入:
string s;
cin>>s; //输入一个字符串
cout<<s<<endl;
string s1,s2;
cin>>s1>>s2; //接连输入两个字符串
cout<<s1<<" "<<s2<<endl;
string s;
while(cin>>s){ //循环输入字符串,字符串之间以空格分隔
cout<<s<<endl;
}
string s;
while(getline(cin,s)){ //按行循环输入字符串,字符串之间以换行分隔
cout<<s<<endl;
}
常用的 string 操作:
s.empty() : 如果 s 为空串,则返回 true,否则返回 false。
s.size() : 返回 s 中字符的个数
s[n] : 返回 s 中位置为 n 的字符,位置从 0 开始计数
s1 + s2 : 把 s1 和 s2 连接成一个新字符串,返回新生成的字符串
s1 = s2 : 把 s1 内容替换为 s2 的副本
v1 == v2 : 比较 v1 与 v2 的内容,相等则返回 true,否则返回 false
!=, <, <=, >, and >= : 保持这些操作符惯有的含义
vector:
初始化vector
vector<T> v1; vector 保存类型为 T 对象。 默认构造函数 v1 为空。
vector<T> v2(v1); v2 是 v1 的一个副本。
vector<T> v3(n, i); v3 包含 n 个值为 i 的元素。
vector<T> v4(n); v4 含有值初始化的元素的 n 个副本。
vector 操作
v.empty() 如果 v 为空,则返回 true,否则返回 false。
v.size() 返回 v 中元素的个数。
v.push_back(t) 在 v 的末尾增加一个值为 t 的元素。
v[n] 返回 v 中位置为 n 的元素。
v1 = v2 把 v1 的元素替换为 v2 中元素的副本。
v1 == v2 如果 v1 与 v2 相等,则返回 true。
!=, <, <=, >, and >= 保持这些操作符惯有的含义。
String word;
Vector<stirng> test;
While(cin>>word){
Text.push_back(word);
}
迭代器:
Iterator:
Vector <int> a;
While(i++ < 10){
A.push_back(i);
}
For(vector<int>::iterator iter = a.begin();iter != a.end();++iter){
Cout<<*iter<<endl;
}
Vector<int>::iterator iter; //可以对数组中的元素进行赋值,修改
Vector<int>::const_iterator iter; //只能读数组中的元素