string对象的定义和初始化
代码示例:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1 = "a";
cout << "s1 = " << s1 << endl; //s1 = a
string s2(s1); //将 s2 初始化为 s1 的一个副本
cout << "s2 = " << s2 << endl; // s2 = a
string s3("an"); //将 s3 初始化为 "mike"
cout << "s3 = " << s3 << endl; // s3 = an
string s4(6, 'b'); // s4 的值为 6 个 'b'
cout << "s4 = " << s4 << endl;
return 0;
}
常用操作
代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s1 = "an";
// 如果s1为空串,则返回true,否则返回false
if( true == s1.empty() ){
cout << "s1 is empty\n";
}else{
cout << "s1 is no empty\n";
}
// 字符串的大小, s1.size()等价于s1.length()
cout << "len = " << s1.size() << endl;
//返回 s1 最大容量
cout << "max_size = " << s1.max_size() << endl;
//取出每一个字符
for(int i = 0; i < s1.size(); i++){
//s1[i]等价于s1.at(i)
cout << i << " = " << s1[i] << endl;
}
string s2 = " dog";
cout << "s1 + s2 = " << s1+s2 << endl;
const char *data = s2.data();
cout << "data = " << data << endl;
const char *buf = "hello";
//string my_str = string(buf);
string my_str = buf;
cout << "my_str = " << my_str << endl;
//s1和s2字符串交换
s1 = "me";
s2 = "love";
s1.swap(s2);
cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
s1.clear();
s1 = "meloveyou";
//取出 s1 从 2 开始后的 3个字符,位置从0开始
s2 = s1.substr(2, 3);
cout << "s2 = " << s2 << endl;
s1 = "me"; //s1 从 4 开始(位置从0开始),插入"love"字符串
s2 = s1.insert(4, "love");
cout << "s2 = " << s2 << endl;
s1="melove"; //删除s1从3开始的2个字符,然后在3位置处插入"an"
s2 = s1.replace(4, 3, "an");
return 0;
}
迭代器操作
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="hellome"; //初始化为"hellome"
//通过迭代器把所有字符元素的值打印出来
string::const_iterator t;
for( t=s.begin(); t!=s.end(); t++){
cout<< *t << ", ";
}
cout << endl;
string::iterator it;
//通过迭代器给所有字符元素赋值为'b'
for( it=s.begin(); it!=s.end(); it++){
*it = 'b';
}
cout << endl;
s = "hellome";
it = s.begin(); //返回指string最开始位置元素的指针(迭代器) //删除指针it+1指向位置的元素,返回指向下一个元素位置的指针(迭代器)
s.erase(it+1);
for( it=s.begin(); it!=s.end(); it++){
cout<< *it << ", ";
}
cout << endl;
s = "aaaaaa";
it = s.begin();
//在位置it后插入3个'b'
s.insert(it, 3, 'b');
return 0;
}