/* ************************************************************************
* Filename: test1.cpp
* Description:
* Version: 1.0
* Created: 2015年07月13日 14时24分40秒
* Revision: none
* Compiler: gcc
* Author: YOUR NAME (),
* Company:
* ************************************************************************/
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main(int argc, char *argv[])
{
string s1 = "mike";
// 如果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 = " jiang";
cout << "s1 + s2 = " << s1+s2 << endl;
// c++ string 和 C char * 相互转换
// string to const char *
const char *str = s1.c_str();
cout << "c_str = " << str << endl;
const char *data = s2.data();
cout << "data = " << data << endl;
// char * to string
const char *buf = "hello, c++";
//string my_str = string(buf);
string my_str = buf;
cout << "my_str = " << my_str << endl;
//s1和s2字符串交换
s1 = "mike";
s2 = "jiang";
s1.swap(s2);
cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
s1.clear();
s1 = "mike";
cout << "s1 = " << s1 << endl;
s1 = "mikejiang";
//取出 s1 从 2 开始后的 4 个字符,位置从0开始
s2 = s1.substr(2, 4);
cout << "s2 = " << s2 << endl;
s1 = "mikejiang";
//删除 s1 从 2 开始后的 4 个字符,位置从0开始
s2 = s1.erase(2, 4);
cout << "s2 = " << s2 << endl;
s1 = "mike";
//s1 从 4 开始(位置从0开始),插入"jiang"字符串
s2 = s1.insert(4, "jiang");
cout << "s2 = " << s2 << endl;
s1="mikejiang";
//删除s1从4开始的5个字符,然后在5位置处插入"tyson"
s2 = s1.replace(4, 5, "tyson");
cout << "s2 = " << s2 << endl;
s1="mikejiang";
//查找字符串"j"在s1中的位置(位置从0开始)
int n = s1.find("j");
cout << "n = " << n << endl;
return 0;
}