string类的使用

string类:

1.string是表示字符串的类;
2.string类的接口与常规容器接口基本相同
3.string底层实现由basic_string模板类实现;

string的构造

string() //用于构造string类的对象;
string(const char*s) //用C-string构造string;
string(size_t n,char c) //string类中含n个c字符
string(const string&s) // 拷贝构造函数(深拷贝)

    string s1;
	string s2("hello world");
	string s3(s2);

string类的容量基本操作
size //返回字符串有效字符长度
length //返回字符串有效长度
capacity //返回空间的大小

string s("hello world");
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;

在这里插入图片描述
**注意:**使用cout需包string的头文件,否则cout无法重载;

empty //检测字符串是否为空,return ture or false;
clear //清空有效字符

string s("hello world");
	cout << s.size() << endl;
	cout << s.length() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;

	//清空字符串,空间不改变
	s.clear();
	cout << s.empty() << endl;
	cout << s.size() << endl;
	cout << s.capacity() << endl;

在这里插入图片描述
clear只是将有效字符串进行清空,并没有改变空间大小;
empty判断为空返回1;

reserve //为字符串预留空间
resize(size_t n ,char c) //将有效字符该为n个,多出来的用字符c填补

s.resize(15, 'w');//扩充到15个有效字符,多处位置为w
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;

	s.reserve(100);
	cout << s.size() << endl;
	cout << s.capacity() << endl;

运行结果:
在这里插入图片描述
可以看到reserve并不会将原来的有效元素改变,只是增容;当reserve的值小于当前空间,不会起到作用(合理利用可以避免增容开销)

string类对象的访问以及遍历
访问
operator[pos] //返回pos位置的字符

	string s1("hello world");
	const string s2("HELLO WORLD");
	cout << s1 << "-" << s2 << endl;
	cout << s1[0] << "-" << s2[0] << endl;
	s1[0] = 'H';
	cout << s1[0] << "-" << s2[0] << endl;

在这里插入图片描述
与c语言访问数组类似,可以使用重载后的[]访问;

遍历
三种方式
使用operator[] ,配合循环
begin() + end() // begin返回一个字符迭代器,end返回最后一个字符下一个位置的迭代器
范围for //适用于c++11;

   //operator[]
	for (size_t i= 0; i < s1.size(); ++i)
	{
		cout << s1[i] << endl;
	}
	//迭代器
	string::iterator it = s1.begin();
	while (it != s1.end())
	{
		cout << *it << endl;
		++it;
	}
	//范围for
	{
		for (auto e : s1)
		{
			cout << e << endl;
		}
	}
}

在这里插入图片描述
可以看到三种方式都可以完成遍历,且可以修改字符。

string类对象的修改操作
push_back //在字符串后尾插字符c
append //在字符串后追加一个字符串
operator+= //在字符串后追加字符串str
c str //返回c格式字符串
find + npos//从字符串pos位置开始找字符c,返回该字符串的位置
substr //在str中从pos位置开始,截取n个字符,然后返回。

string str;
	str.push_back(' ');
	str.append("hello ");
	str += 'w';
	str += "orld";
	cout << str << endl;
	cout << str.c_str() << endl;

在这里插入图片描述
push_back接口与append的区别是前者插入字符,后者插入字符串
operator+=可以同时实现上面俩个接口,区别为插入字符使用‘’ 单引号,插入字符串需使用“”,如果使用错误,编译器会发生截断。

find + npos//从字符串pos位置开始找字符c,返回该字符串的位置
substr //在str中从pos位置开始,截取n个字符,然后返回。

string url("https://editor.csdn.net/md/?articleId=106225126");
	size_t pos = url.find("://");
	if (pos != string::npos)
	{
		cout << url.substr(pos) << endl;
	}

在这里插入图片描述
npos 为string里面的一个静态成员变量默认为-1;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值