【C++】String类、String类的常用接口说明及其使用、STL中的迭代器使用

C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP(Object Oriented Programming,面向对象程序设计)的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。所以C++中有了String类,而且在日常的生活工作中,为了简单、方便、快捷,基本都使用string类。

一、标准库中的String类

  • 字符串是表示字符序列的类
  • 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
  • string类是使用char(即作为它的字符类型,使用它的默认char_traits和分配器类型)
  • string类是basic_string模板类的一个实例,它使用char来实例化basic_string模板类,并用char_traits和allocator作为basic_string的默认参数。
  • 注意,这个类独立于所使用的编码来处理字节:如果用来处理多字节或变长字符(如UTF-8)的序列,这个类的所有成员(如长度或大小)以及它的迭代器,将仍然按照字节(而不是实际编码的字符)来操作。

其实在它的底层,String类就是一个字符串数组,该数组支持动态增长。 

【总结】

1. string是表示字符串的字符串类
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
3. string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator>string;
4. 不能操作多字节或者变长字符的序列。

使用string类时,必须包含头文件以及using namespace std;
 

二、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(const string&s, size_t n)

                      用s中的前n个字符构造新的string类对象

string(const string& s,size_t pos,size_t len = npos) 用s中的第pos个位置处取n个字符构造string类对象
void TestString()
{
	string s1; // 构造空的string类对象s1
	string s2("hello bit"); // 用C格式字符串构造string类对象s2
	string s3(10, 'a'); // 用10个字符'a'构造string类对象s3
	string s4(s2); // 拷贝构造s4
	string s5(s3, 5); // 用s3中前5个字符构造string对象s5
	string s6("world");
	s1 = s6;//赋值

	string file("file.cpp");
	string suffix(file, 4, 4);//从第四个位置开始取4个字符
	cout << suffix << endl;

	string path("c:\\test.c", 3);
	cout << path << endl;//用前n个字符构造
}

 

string类对象的容量操作

函数名称 功能说明
size_t size() const 返回字符串有效字符长度
size_t length() const 返回字符串有效字符长度
size_t capacity ( ) const 返回空间总大小
bool empty ( ) const 检测字符串释放为空串,是返回true,否则返回false
void clear() 清空有效字符
void resize ( size_t n, char c ) 将有效字符的个数该成n个,多出的空间用字符c填充
void resize ( size_t n ) 将有效字符的个数改成n个,多出的空间用0填充,少的地方删除只保留n个字符
void reserve ( size_t res_arg=0 ) 为字符串预留空间
void test_string4()
{
// 注意:string类对象支持直接用cin和cout进行输入和输出
	string s1("hello");
	cout << s1 << endl;
	cout << s1.size() << endl;
	cout << s1.length() << endl;
	cout << s1.capacity() << endl;
	cout << s1.max_size() << endl;
	cout << endl;
// 将s1中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
	s1.clear();
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << endl;

 resize

void test_string4()
{
	string s;
// 将s中有效字符个数增加到10个,多出位置用'a'进行填充
// “aaaaaaaaaa”
	s.resize(10, 'a');
	cout << s.size() << endl;
	cout << s.capacity() << endl;
// 将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
// "aaaaaaaaaa\0\0\0\0\0"
// 注意此时s中有效字符个数已经增加到15个
	s.resize(15);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;
// 将s中有效字符个数缩小到5个
	s.resize(5);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	cout << s << endl;
}

reserve 

void TestString2()
{
	string s;
	// 测试reserve是否会改变string中有效元素个数
	s.reserve(100);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
	// 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
	s.reserve(50);
	cout << s.size() << endl;
	cout << s.capacity() << endl;
}

【注意】 

1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。

2. clear()只是将string中有效字符清空,不改变底层空间大小。

3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。

4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserve不会改变容量大小。 

 

string类对象的访问操作

函数名称 功能说明
char& operator[] ( size_t pos ) 返回pos位置的字符,const string类对象调用
const char& operator[] ( size_t pos )
const
返回pos位置的字符,非const string类对象调
void TestString()
{
	string s1("hello World");
	const string s2("Hello World");
	cout << s1 << " " << s2 << endl;
	cout << s1[0] << " " << s2[0] << endl;
	s1[0] = 'H';
	cout << s1 << endl;
	for (size_t i = 0; i < s1.size(); ++i)
	{
		cout << s1[i] << endl;
	}
	// s2[0] = 'h'; 代码编译失败,因为const类型对象不能修改
}


string类对象的修改操作

函数名称 功能说明
void push_back(char c) 在字符串后尾插字符c
string& append (const char* s); 在字符串后追加一个字符串
string& operator+=(const string&
str)
在字符串后追加字符串str
string& operator+=(const char* s) 在字符串后追加C个数字符串
string& operator+=(char c) 在字符串后追加字符c
const char* c_str( )const 返回C格式字符串
size_t find (char c, size_t pos =
0)const
从字符串pos位置开始往后找字符c,返回该字符在
字符串中的位置
size_t rfind(char c, size_t pos = npos) 从字符串pos位置开始往前找字符c,返回该字符在
字符串中的位置
string substr(size_t pos = 0, size_t n
= npos)const
在str中从pos位置开始,截取n个字符,然后将其
返回
void TestString()
{
	string str;
	str.push_back(' '); // 在str后插入空格
	str.append("hello"); // 在str后追加一个字符"hello"
	str += 'w'; // 在str后追加一个字符'b'
	str += "orld"; // 在str后追加一个字符串"it"
	cout << str << endl;
	cout << str.c_str() << endl; // 以C语言的方式打印字符串
}
void TestString()
{
// 获取file的后缀
	string file("string.cpp");
	size_t pos = file.rfind('.');
	string suffix(file.substr(pos, file.size() - pos));
	cout << suffix << endl;
}
void TestString()
{
// npos是string里面的一个静态成员变量
// static const size_t npos = -1;
// 取出url中的域名
	string url("http://www.cplusplus.com/reference/string/string/find/");
	cout << url << endl;
	size_t start = url.find("://");
	if (start == string::npos)
	{
		cout << "invalid url" << endl;
		return;
	}
	start += 3;
	size_t finish = url.find('/', start);
	string address = url.substr(start, finish - start);
	cout << address << endl;

// 删除url的协议前缀
	pos = url.find("://");
	url.erase(0, pos + 3);
	cout << url << endl;
}

【注意】

1. 在string尾部追加字符时,s.push_back(c) / s.append(1, c) / s += 'c'三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。

2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

 

string类非成员函数

函数 功能说明
operator+ 尽量少用,因为效率低
operator>> 输入运算符重载
operator<< 输出运算符重载
getline 获取一行字符串
relational operators 大小比较

 

三、STL中迭代器的使用-不破坏封装的情况下去访问容器

迭代器的接口我们可以看到如下图所示:

【C++】String类、String类的常用接口说明及其使用、STL中的迭代器使用

下面举例三种容器中正向迭代器的使用~ 

String 

int StrToInt1(string str)
{
	int value = 0;
	
	string::iterator it = str.begin();
	while (it != str.end())
	{
		value *= 10;
		value += (*it - '0');
		++it;
	}
	return value;
}

Vector

	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	vector<int>::iterator vit = v.begin();
	while (vit != v.end())
	{
		cout << *vit << endl;
		++vit;
	}

List

	list<int> l;
	l.push_back(10);
	l.push_back(20);
	l.push_back(30);
	list<int>::iterator lit = l.begin();
	while (lit != l.end())
	{
		cout << *lit << endl;
		++lit;
	}