#include <iostream>
#include <string>
using namespace std;
int main()
{
string = "abc", b = "bb";
swap(a, b);
cout << a << " " << b << endl;
return 0;
}
2. s.size(); 或 s.length(); // 返回字符串字符个数
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abc";
cout << s.size() << " " << s.length() << endl;
return 0;
}
3. s.empty(); // 返回字符串是否为空,若空则true,非空则false
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abc";
if(s.empty()) cout << "empty" << endl;
else cout << "not empty" << endl;
return 0;
}
4.s.append(ss); // 添加函数,将ss添加到后方
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abc";
cout << s << endl;
s.append("def");
cout << s << endl;
return 0;
}
5. s.insert(2, ss); // 插入函数,在s字符串的第二个字符后插入ss
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abc";
cout << s << endl;
s.insert(2, "fff");
cout << s << endl;
return 0;
}
6. s = s.substr(n); // 删除前n个字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdef";
cout << s << endl;
s = s.substr(2);
cout << s << endl;
return 0;
}
7. int pos = a.find('A', 0); // 前面位置开始查找,查找A字符最早出现的位置,若没找到,则返回string::npos
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdefa";
int posA = s.find("a", 0);
cout << posA << endl;
int posC = s.find("c", 0);
cout << posC << endl;
return 0;
}
8. s.erase(0, 2); // 删除函数,删除字符串从0位置起的后2个字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcdef";
cout << s << endl;
s.erase(0, 2);
cout << s << endl;
return 0;
}
9. s.substr(2, 5); // 复制函数,复制字符串从2位置开始,长度为5的字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "0123456789";
string s = str.substr(2, 5);
cout << s << endl;
return 0;
}