C++初级--string的用法

目录

1.string类简介

2.String类的常用接口说明

string类对象的常见构造

string类的容量操作

 string的访问及遍历

 string类对象的修改操作

string类对象的扩容

reserve和resize的区别

 c_str

string类的增删查改

 插入和删除

string比较大小

字符串和整型互转



1.string类简介

【标准库中的string类】:

  1. 字符串是表示字符序列的类
  2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
  4. 这个类独立于所使用的编码来处理字节。如果用来处理多字节或变长字符,如UTF-8序列,这个类的所有成员以及它的迭代器,将仍然按照字节而不是实际编码来操作。总而言之,不能操作多字节或者变长字符的序列。
  5. 在使用string类时,必须包含头文件#include<string>

2.String类的常用接口说明

string类对象的常见构造

std::string(constructor) 对于这个文档会对C++中的string类有详细解释。

  • string()        构造空的string类对象,即空字符串
  • string (const string& str)        用另一个类对象拷贝构造当前类对象
  • string(const char* s)         用字符串初始化
  • string (const string& str, size_t pos, size_t len = npos)        用另一个类对象的pos位置直到len位置初始化当前类对象,当len有值且小于字符串长度,那么初始化的就是pos到len的位置,如果len超过字符串长度,或者没有给值,用了npos缺省值,那么截取的str范围就是pos的位置直到最后,有多少取多少。
    • 这里pos和npos在文档中都有解释,npos是len的缺省值,因为npos是一个静态变量,值为-1,它的补码是32个1,size_t变成无符号数,补码是31个1,对应的原码数字是42亿,这就造成了范围远远大于字符串长度。
  • string (const char* s, size_t n)        用一个字符串,取字符串的前n个来初始化字符类对象。但是对于这个用法有点鸡肋,如果想取前n个来初始化,直接用前n个初始化就好了。
  • string (size_t n, char c)        用n个char字符c来初始化字符类对象。
int main()
{
	string s1;
	string s2("hello world");
	string s3(s2);

	cin >> s1;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;

	string s4(s2, 2, 6);//很少用这个
	cout << s4 << endl;

	string s5(s2, 2);//没给范围或者范围超过字符串长度,有多少取多少
	string s6(s2, 2, 100);
	cout << s5 << endl;
	cout << s6 << endl;

	string s7("hello world", 3);
	//string s7("hel");
	cout << s7 << endl;
	string s8("i am a student.", 4);
	cout << s8 << endl;

	string s9(10, '!');
	cout << s9 << endl;


	return 0;
}

string类的容量操作

  1. size        返回字符串有效字符长度(不包括\0)
  2. length       同上
  3. max_size       返回最大字符串长度,一般长度是42亿(实际意义不大)
  4. capacity       查看空间容量大小是多少
  5. clear       把有效数据全清理掉
  6. empty       判断是否为空
  7. shrink_to_fit(C++11)       释放口面所有的容量
string s1;
	cin >> s1;
	cout << s1.size() << endl;
	cout << s1.length() << endl;
	cout << s1.max_size() << endl;

	cout << s1.capacity() << endl;
	s1.clear();
	cout << s1 << endl;
	cout << s1.capacity() << endl;//只是把数据清掉,容量没有清掉

 string的访问及遍历

  • operator[]        返回pos位置的字符,实际上是[]的一个重载。底层代码返回值为char&,起初是为了减少拷贝,但是在这里是为了得到字符串,在有些代码实现中,返回字符的引用,可以修改该位置的字符串值(出了作用域还在,都在堆上)
  • at[]        与operator[]类似,但是二者检查越界有区别,operaotr[]通过断言检查越界,at
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值