当前位置: 代码网 > it编程>编程语言>C/C++ > c++初阶知识——string类详解

c++初阶知识——string类详解

2024年07月28日 C/C++ 我要评论
C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。
 

目录

 

前言:

1.标准库中的string类

1.1 auto和范围for

auto

 范围for

1.2 string类常用接口说明

1.string类对象的常见构造

1.3 string类对象的访问及遍历操作

1.4. string类对象的修改操作 

 1.5 string类非成员函数

2.string类的模拟实现 

2.1 经典的string类问题 

2.2 浅拷贝 

2.3 深拷贝 

2.4 string类实现 

3.写时拷贝 


前言:

c语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,c标准库中提供了一些str系列
的库函数,但是这些库函数与字符串是分离开的,不太符合oop的思想,而且底层空间需要用户
自己管理,稍不留神可能还会越界访问。

1.标准库中的string类

1.1 auto和范围for

auto

(1)在早期c/c++中auto的含义是:使用auto修饰的变量,是具有自动存储器的局部变量后来这个不重要了。c++11中,标准委员会变废为宝赋予了auto全新的含义即:auto不再是一个存储类型指示符,而是作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期
推导而得

(2)用auto声明指针类型时,用auto和auto*没有任何区别,但用auto声明引用类型时则必须加&

(3)当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量

(4)auto不能作为函数的参数,可以做返回值,但是建议谨慎使用

(5)auto不能直接用来声明数组

#include <map>
using namespace std;
int main()
{
std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
"橙子" }, {"pear","梨"} };
// auto的用武之地
//std::map<std::string, std::string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
范围for
对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此
c++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围
内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。
范围for可以作用到数组和容器对象上进行遍历
范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。
2.3 string类的常用接口说明(注意下面我只讲解最常用的接口)
1. string类对象的常见构造
return 0;
}

 范围for

(1)对于一个有范围的集合而言,由程序员来说明循环的范围是多余的,有时候还会容易犯错误。因此c++11中引入了基于范围的for循环。for循环后的括号由冒号“ :”分为两部分:第一部分是范围内用于迭代的变量,第二部分则表示被迭代的范围,自动迭代,自动取数据,自动判断结束。

(2)范围for可以作用到数组和容器对象上进行遍历

(3)范围for的底层很简单,容器遍历实际就是替换为迭代器,这个从汇编层也可以看到。

示例:

#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
   int array[] = { 1, 2, 3, 4, 5 };
   // c++98的遍历
   for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
  {
       array[i] *= 2;
  }
   for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
  {
       cout << array[i] << endl;
  }
   // c++11的遍历
   for (auto& e : array)
       e *= 2;
   for (auto e : array)
       cout << e << " " << endl;
   string str("hello world");
   for (auto ch : str)
  {
       cout << ch << " ";
  }
   cout << endl;
return 0;
}

1.2 string类常用接口说明

1.string类对象的常见构造

注意:
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的底层空间总大小时,reserver不会改变容量大小。 

1.3 string类对象的访问及遍历操作

1.4. string类对象的修改操作 

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


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

 1.5 string类非成员函数

2.string类的模拟实现 

2.1 经典的string类问题 

// 为了和标准库区分,此处使用string
class string
{
public:
/*string()
:_str(new char[1])
{*_str = '\0';}
*/
//string(const char* str = "\0") 错误示范
//string(const char* str = nullptr) 错误示范
string(const char* str = "")
{
// 构造string类对象时,如果传递nullptr指针,可以认为程序非
if (nullptr == str)
{
assert(false);
return;
}
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
~string()
{
if (_str)
{
delete[] _str;
_str = nullptr;
}
}
private:
char* _str;
};
// 测试
void teststring()
{
string s1("hello bit!!!");
string s2(s1);
}

 

2.2 浅拷贝 

就像一个家庭中有两个孩子,但父母只买了一份玩具,两个孩子愿意一块玩,则万事大吉,万一
不想分享就你争我夺,玩具损坏。

所以可以采用深拷贝解决浅拷贝问题,即:每个对象都有一份独立的资源,不要和其他对象共享。父母给每个孩子都买一份玩具,各自玩各自的就不会有问题了。 

2.3 深拷贝 

 

2.4 string类实现 

 能否写好string反映出我们对类和对象知识的理解是否深刻,这一块知识如果理解得不够深刻,我们的c++程序就会经常出现此类问题。为了方便管理,我们将string的实现分为3个文件是实现:

string.h :

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;


namespace myobject
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;
		string& operator+=(char ch);
		string& operator+=(const char* str);
		void append(const char* str);
		void insert(size_t  pos, char ch);
		void insert(size_t  pos, const char* str);
		void erase(size_t pos, size_t len = npos);
		size_t find(char ch, size_t pos);
		size_t find(const char* str, size_t pos);
		string substr(size_t pos, size_t len);

		string& operator=(const string& s);

		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}

		string(const string& s)
		{
			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
		}

		void test0_01();

		void reserve(size_t n);
		void push_back(char ch);

		/*string()
			:_str(new char[1] {'\0'})
			,_size(0)
			,_capacity(0)
		{}*/

		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator begin() const
		{
			return _str;
		}

		const_iterator end() const
		{
			return _str + _size;
		}







		const char* c_str() const
		{
			return _str;
		}

		size_t size()
		{
			return _size;
		}

		size_t capacity()
		{
			return _capacity;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);

			return _str[pos];
		}

		const	char& operator[](size_t pos) const
		{
			assert(pos < _size);

			return _str[pos];
		}


		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;


		}


	private:
		char* _str;
		size_t _size;
		size_t _capacity;
		static const size_t npos;
	};

	ostream& operator<<(ostream& out, const string& s);
	istream& operator>>(istream& in, string& s);
}

string.cpp :

#define _crt_secure_no_warnings 1
#include"string.h"

namespace myobject
{
	const size_t string::npos = -1;

	string string::substr(size_t pos, size_t len)
	{
		assert(pos < _size);
		if (len > _size - pos)
		{
			len = _size - pos;
		}

		string sub;
		sub.reserve(len);
		for (size_t i = 0; i < len; i++)
		{
			sub += _str[pos + i];
		}
		return sub;
	}

	size_t string::find(char ch, size_t pos)
	{
		assert(pos < _size);
		for (size_t i = 0; i < _size; i++)
		{
			if (_str[i] == ch)
			{
				return i;
			}
		}
		return npos;

	}
	size_t string::find(const char* str, size_t pos)
	{
		assert(pos < _size);
		const char* ptr = strstr(_str + pos, str);
		if (ptr == nullptr)
		{
			return npos;
		}
		else
		{
			return ptr - _str;
		}
	}
	void string::erase(size_t pos, size_t len)
	{
		assert(pos < _size);
		if (len >= _size - pos)
		{
			_str[pos] = '0';
			_size = pos;
		}
		else
		{
			for (size_t i = pos + len; i < _size; i++)
			{
				_str[i - len] = _str[i];
			}
			_size -= len;
		}

	}

	void string::insert(size_t pos, char ch)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		size_t end = _size + 1;
		if (end > pos)
		{
			_str[end] = _str[end - 1];
			end--;
		}
		_str[pos] = ch;
		_size++;
	}//插入单个字符

	void string::insert(size_t  pos, const char* str)
	{
		assert(pos <= _size);
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			reserve(len + _size == 2 * _capacity ? len + _size : 2 * _capacity);
		}
		size_t end = _size + len;
		while (end - 2 > pos)
		{
			_str[end] = _str[end - len];
			end--;
		}
		for (int i = 0; i < len; i++)
		{
			_str[pos + i] = str[i];
		}
		_size += len;

	}

	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			reserve(len + _size == 2 * _capacity ? len + _size : 2 * _capacity);
		}
		strcpy(_str + _size, str);
		_size += len;
		//	_str[_size] = '\0';

	}

	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}//扩容
	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
	}//尾插

	string& string::operator+=(char ch)
	{
		push_back(ch);
		return *this;
	}

	string& string::operator=(const string& s)
	{
		if (this != &s)
		{
			delete[] _str;
			_str = new char[s._capacity + 1];
			strcpy(_str, s._str);
			_size = s._size;
			_capacity = s._capacity;
			return *this;
		}
	}

	ostream& operator<<(ostream& out, const string& s)
	{
		for (auto ch : s)
		{
			out << ch;
		}
		return out;
	}
	istream& operator>>(istream& in, string& s)
	{
		char ch;
		ch = in.get();
		while (ch != ' ' && ch != '\n')
		{
			s += ch;
			ch = in.get();
		}
		return in;
	}
}

test.cpp :

#define _crt_secure_no_warnings 1
#include"string.h"

namespace myobject
{
	void test_01()
	{

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

		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		for (int i = 0; i < s2.size(); i++)
		{
			s2[i] += 2;
		}
		cout << s2.c_str() << endl;

		s2 += 'a';
		s2 += 'b';

		string::iterator it = s2.begin();
		while (it != s2.end())
		{
			cout << *it << " ";
			it++;
		}
		cout << endl;

		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		cout << endl;
		s2.insert(0, '$');
		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		cout << endl;
		s2.insert(8, "%%%%%%%");
		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		cout << endl;
		s2.erase(8, 100);
		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		cout << endl;
		/*s2.append("hehe");
		for (auto ch : s2)
		{
			cout << ch << " ";
		}
		s2 += "hello";
		for (auto ch : s2)
		{
			cout << ch << " ";
		}*/
	}
	void test02()
	{
		string s1("hello world");
		string s2 = s1.substr(6, 5);

		cout << s2.c_str() << endl;

		string s3("hello bit");
		s2 = s3;
		cout << s1 << endl;
		cout << s2 << endl;

		cin >> s1;
		cout << s1 << endl;

	}
}
int main()
{
	myobject::test02();
	//myobject::test_01();
	return 0;
}

3.写时拷贝 

本章完。 

 

 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com