STL string

头文件

#include <string>

定义

string str;

函数

  • string(const char *s):用字符串s初始化
  • string(int n,char c):用n个字符c初始化
  • int size():返回当前字符串的大小
  • bool empty():判断当前字符串是否为空
  • string substr(int pos = 0, int n = npos) const:返回pos开始的n个字符组成的字符串
  • int find(char c, int pos = 0) const:从pos开始查找字符c在当前字符串的位置,找不到返回-1
  • void swap(string &s2):交换当前字符串与s2的值
  • string &insert(int p0, const char *s):在p0处插入字符串s
  • string &erase(int pos = 0, int n = npos):删除pos开始的n个字符

例子

#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
char *s = "abcd";
string str(s);
string st;
int main()
{
	cout << str << endl;
	cout << str.size() << endl;
	cout << str.empty() << endl;
	st = str.substr(2, 2);
	cout << st << endl;
	cout << str.find('d', 0) << endl;
	str.swap(st);
	cout << str << endl;
	str.insert(1, s);
	cout << str << endl;
	str.erase(1, 1);
	cout << str << endl;
}
原文地址:https://www.cnblogs.com/xuyixuan/p/9434532.html