#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
//创建对象
string s1,s2,s;
//赋值
s1="Hello";
s2=" World";
s="Hello World";
//尾部添加
//'+' '+=' 可添加字符,字符串
s1 += s2; //s1="Hello World"
s1 +=" World"; //s1="Hello World"
s1 +='W'; //s1="HelloW"
//append() 只能添加字符串
s1.append(s2); //s1="Hello World"
s1.append(" World"); //s1="Hello World"
//push_back() 只能添加字符
s1.push_back('W'); //s1="HelloW"
//插入 insert()
s1.insert(0,"World "); //s1="World Hello"
s1.insert(0,s2); //s1=" WorldHello"
//删除 erase()
s.erase(5,3); //s="Hellorld"
s.erase(s.begin()+2,s.end()-3); //s="Herld"
//查找 find() 返回下标值,从0开始
s.find('o'); //返回4
s.find("llo"); //返回2,返回第一个字符出现的下标
//替换 replace()
s.replace(6,5,"good"); //从第六个开始,将连续的五个字符替换成 good s="Hello good"
s.replace(s.find('W'),5,"good"); //s="Hello good"
//返回长度
s.size();
s.length(); //均返回11
//判断是否为空
s.empty(); //空,返回1,否则返回0
//反向排序 reverse()
reverse(s.begin(),s.end()); //s="dlroW olleH"
return 0;
}
比较 compare() 比对方大返回1,小返回-1,相等返回0
string str1="green apple";
string str2="red apple";
string str3="apple";
if(str3.compare("apple") == 0)
cout << str3 << " is an apple!" << endl;
if(str1.compare(str2) !=0)
cout << str1 << " is not " << str2 <<endl;
if(str1.compare(6,5, "apple") == 0)
cout << "still, " << str1 << " is an apple!" << endl;
if(str2.compare(str2.size()-5, 5, "apple") == 0)
cout << "and " << str2 << " is an apple!" <<endl;
if(str1.compare(6, 5, str2, 4, 5) == 0)
cout << "therefore, both are apples!" << endl;
string对象作为vector元素 类似字符串数组
vector <string> str;
str.push_back("dog");
str.push_back("and");
str.push_back("cat");
cout << s[0] <<endl; //返回dog
cout << s[1] <<endl; //返回and
cout << s[0][2] <<endl; //返回g
cout << s[2][1] <<endl; //返回a
cout << s[0].size() <<endl; //返回3