string类

1. 为什么学习string类?

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

2. 标准库中的string类

2.1 string

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

总结: 

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

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

2.2 string类的常用接口说明

1. string类对象的常见构造

(constructor)函数名称
功能说明
string( ) 
构造空的string类对象,即空字符串
string(const char* s)
用C-string来构造string类对象
string(size_t n, char c)
string类对象中包含n个字符c
string(const string&s)
拷贝构造函数
void Teststring()
{
	string s1; // 构造空的string类对象s1
	string s2("hello China"); // 用C格式字符串构造string类对象s2
	string s3(s2); // 拷贝构造s3
}

2. string类对象的容量操作

函数名称
功能说明
size
返回字符串有效字符长度
length
返回字符串有效字符长度
capacity
返回空间总大小
empty
检测字符串释放为空串,是返回true,否则返回false
clear
清空有效字符
reserve
为字符串预留空间**
resize
将有效字符的个数该成n个,多出的空间用字符c填充
注意:
  1. 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 不会改变容量大小。

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

函数名称
功能说明
operator[ ]
返回pos位置的字符,const string类对象调用
begin+end
begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
rbegin+rend
begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
范围for
C++11支持更简洁的范围for的新遍历方式

 4.string类对象的修改操作

函数名称功能说明
push_back
在字符串后尾插字符 c
append
在字符串后追加一个字符串
operator+=
在字符串后追加字符串 str
c_str
返回 C 格式字符串
find + npos
从字符串 pos 位置开始往后找字符 c ,返回该字符在字符串中的位置
rfind
从字符串 pos 位置开始往前找字符 c ,返回该字符在字符串中的位置
substr
str 中从 pos 位置开始,截取 n 个字符,然后将其返回
注意:
  1. string 尾部追加字符时, s.push_back(c) / s.append(1, c) / s += 'c' 三种的实现方式差不多,一般情况下string 类的 += 操作用的比较多, += 操作不仅可以连接单个字符,还可以连接字符串。
  2. string 操作时,如果能够大概预估到放多少字符,可以先通过 reserve 把空间预留好。

5. string类非成员函数

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

3.总结

//string.h
#pragma once

namespace bit
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;

		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}


		const_iterator begin() const
		{
			return _str;
		}

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

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

		// 不能这么初始化空对象
		/*string()
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
			{}*/

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

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

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

			strcpy(_str, str);
		}

		// 传统写法
		// s2(s1)
		//string(const string& s)
		//	:_str(new char[s._capacity+1])
		//	, _size(s._size)
		//	, _capacity(s._capacity)
		//{
		//	strcpy(_str, s._str);
		//}

		 s1 = s3
		 s1 = s1
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{
		//		char* tmp = new char[s._capacity + 1];
		//		strcpy(tmp, s._str);

		//		delete[] _str;

		//		_str = tmp;
		//		_size = s._size;
		//		_capacity = s._capacity;
		//	}

		//	return *this;
		//}

		// 现代写法 -- 资本主义/老板思维
		// s2(s1)
		void swap(string& tmp)
		{
			::swap(_str, tmp._str);
			::swap(_size, tmp._size);
			::swap(_capacity, tmp._capacity);
		}

		// s2(s1)
		string(const string& s)
			:_str(nullptr)
			, _size(0)
			, _capacity(0)
		{
			string tmp(s._str);
			swap(tmp); //this->swap(tmp);
		}

		// s1 = s3
		//string& operator=(const string& s)
		//{
		//	if (this != &s)
		//	{
		//		//string tmp(s._str);
		//		string tmp(s);
		//		swap(tmp); // this->swap(tmp);
		//	}

		//	return *this;
		//}

		// s1 = s3
		// s顶替tmp做打工人
		string& operator=(string s)
		{
			swap(s);
			return *this;
		}

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

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

		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

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

			return _str[pos];
		}

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

			return _str[pos];
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;

				_str = tmp;
				_capacity = n;
			}
		}

		void resize(size_t n, char ch = '\0')
		{
			if (n > _size)
			{
				// 插入数据
				reserve(n);
				for (size_t i = _size; i < n; ++i)
				{
					_str[i] = ch;
				}
				_str[n] = '\0';
				_size = n;
			}
			else
			{
				// 删除数据
				_str[n] = '\0';
				_size = n;
			}
		}

		void push_back(char ch)
		{
			// 满了就扩容
			/*if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}

			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';*/
			insert(_size, ch);
		}

		void append(const char* str)
		{
			//size_t len = strlen(str);

			 满了就扩容
			 _size + len  8  18  10  
			//if (_size + len > _capacity)
			//{
			//	reserve(_size+len);
			//}

			//strcpy(_str + _size, str);
			strcat(_str, str); 需要找\0,效率低
			//_size += len;
			insert(_size, str);
		}

		/*void append(const string& s)
		{
		append(s._str);
		}

		void append(size_t n, char ch)
		{
		reserve(_size + n);
		for (size_t i = 0; i < n; ++i)
		{
		push_back(ch);
		}
		}*/

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

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

		string& insert(size_t pos, char ch)
		{
			assert(pos <= _size);

			// 满了就扩容
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}

			 挪动数据
			//int end = _size;
			//while (end >= (int)pos)
			//{
			//	_str[end + 1] = _str[end];
			//	--end;
			//}
			size_t end = _size + 1;
			while (end > pos)
			{
				_str[end] = _str[end - 1];
				--end;
			}

			_str[pos] = ch;
			++_size;

			return *this;
		}

		string& insert(size_t pos, const char* str)
		{
			assert(pos <= _size);
			size_t len = strlen(str);
			if (_size + len > _capacity)
			{
				reserve(_size + len);
			}

			// 挪动数据
			size_t end = _size + len;
			while (end >= pos + len)
			{
				_str[end] = _str[end - len];
				--end;
			}

			strncpy(_str + pos, str, len);
			_size += len;

			return *this;
		}

		void erase(size_t pos, size_t len = npos)
		{
			assert(pos < _size);

			if (len == npos || pos + len >= _size)
			{
				_str[pos] = '\0';
				_size = pos;
			}
			else
			{
				strcpy(_str + pos, _str + pos + len);
				_size -= len;
			}
		}

		void clear()
		{
			_str[0] = '\0';
			_size = 0;
		}

		size_t find(char ch, size_t pos = 0) const
		{
			assert(pos < _size);

			for (size_t i = pos; i < _size; ++i)
			{
				if (ch == _str[i])
				{
					return i;
				}
			}

			return npos;
		}

		// "hello world bit"
		size_t find(const char* sub, size_t pos = 0) const
		{
			assert(sub);
			assert(pos < _size);

			// kmp/bm
			const char* ptr = strstr(_str + pos, sub);
			if (ptr == nullptr)
			{
				return npos;
			}
			else
			{
				return ptr - _str;
			}
		}

		// "hello world bit"
		string substr(size_t pos, size_t len = npos) const
		{
			assert(pos < _size);
			size_t realLen = len;
			if (len == npos || pos + len > _size)
			{
				realLen = _size - pos;
			}

			string sub;
			for (size_t i = 0; i < realLen; ++i)
			{
				sub += _str[pos + i];
			}

			return sub;
		}

		bool operator>(const string& s) const
		{
			return strcmp(_str, s._str) > 0;
		}

		bool operator==(const string& s) const
		{
			return strcmp(_str, s._str) == 0;
		}

		bool operator>=(const string& s) const
		{
			return *this > s || *this == s;
		}

		bool operator<=(const string& s) const
		{
			return !(*this > s);
		}

		bool operator<(const string& s) const
		{
			return !(*this >= s);
		}

		bool operator!=(const string& s) const
		{
			return !(*this == s);
		}
	private:
	
		// < 16 字符串存在buff数组中
		// >= 16 存在)_str指向堆空间上
		// char _buff[16];
		size_t _capacity;
		size_t _size;
		char* _str;
	public:
		// const static 语法特殊处理
		// 直接可以当成定义初始化
		const static size_t npos = -1;
	};

	ostream& operator<<(ostream& out, const string& s)
	{
		for (size_t i = 0; i < s.size(); ++i)
		{
			out << s[i];
		}

		return out;
	}

	//istream& operator>>(istream& in, string& s)
	//{
	//	// 输入字符串很长,不断+=,频繁扩容,效率很低
	//	char ch;
	//	//in >> ch;
	//	ch = in.get();
	//	s.reserve(128);
	//	while (ch != ' ' && ch != '\n')
	//	{
	//		//size_t old = s.capacity();
	//		s += ch;
	//		if (s.capacity() != old)
	//		{
	//			cout << old << "扩容" << s.capacity() << endl;
	//		}

	//		ch = in.get();
	//	}

	//	return in;
	//}

	istream& operator>>(istream& in, string& s)
	{
		s.clear();

		char ch;
		ch = in.get();

		const size_t N = 32;
		char buff[N];
		size_t i = 0;

		while (ch != ' ' && ch != '\n')
		{
			buff[i++] = ch;
			if (i == N - 1)
			{
				buff[i] = '\0';
				s += buff;
				i = 0;
			}

			ch = in.get();
		}

		buff[i] = '\0';
		s += buff;

		return in;
	}

	//size_t string::npos = -1;

	void test_string1()
	{
		/*std::string s1("hello world");
		std::string s2;*/
		string s1("hello world");
		string s2;

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

		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;

		for (size_t i = 0; i < s1.size(); ++i)
		{
			s1[i]++;
		}

		for (size_t i = 0; i < s1.size(); ++i)
		{
			cout << s1[i] << " ";
		}
		cout << endl;
	}

	void test_string2()
	{
		string s1("hello world");
		string::iterator it = s1.begin();
		while (it != s1.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;

		it = s1.begin();
		while (it != s1.end())
		{
			*it += 1;
			++it;
		}
		cout << endl;

		for (auto ch : s1)
		{
			cout << ch << " ";
		}
		cout << endl;
	}

	void test_string3()
	{
		string s1("hello world");
		string s2(s1);
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		s2[0] = 'x';
		cout << s1.c_str() << endl;
		cout << s2.c_str() << endl;

		string s3("111111111111111111111111111111");
		s1 = s3;
		cout << s1.c_str() << endl;
		cout << s3.c_str() << endl;

		s1 = s1;

		cout << s1.c_str() << endl;
		cout << s3.c_str() << endl;
	}

	void test_string4()
	{
		string s1("hello world");
		string s2("xxxxxxx");

		s1.swap(s2);
		swap(s1, s2);
	}

	void test_string5()
	{
		string s1("hello");
		cout << s1.c_str() << endl;
		s1.push_back('x');
		cout << s1.c_str() << endl;
		cout << s1.capacity() << endl;

		s1 += 'y';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		s1 += 'z';
		cout << s1.c_str() << endl;
		cout << s1.capacity() << endl;
	}

	void test_string6()
	{
		string s1("hello");
		cout << s1.c_str() << endl;
		s1 += ' ';
		s1.append("world");
		s1 += "bit hello";
		cout << s1.c_str() << endl;

		s1.insert(5, '#');
		cout << s1.c_str() << endl;

		s1.insert(0, '#');
		cout << s1.c_str() << endl;
	}

	void test_string7()
	{
		string s1("hello");
		cout << s1.c_str() << endl;

		s1.insert(2, "world");
		cout << s1.c_str() << endl;

		s1.insert(0, "world ");
		cout << s1.c_str() << endl;
	}

	void test_string8()
	{
		string s1("hello");
		s1.erase(1, 10);
		cout << s1.c_str() << endl;


		string s2("hello");
		s2.erase(1);
		cout << s2.c_str() << endl;

		string s3("hello");
		s3.erase(1, 2);
		cout << s3.c_str() << endl;
	}

	void test_string9()
	{
		/*	string s1;
			cin >> s1;
			cout << s1 << endl;*/

		string s1("hello");
		cout << s1 << endl; // operator<<(cout, s1)
		cout << s1.c_str() << endl;
		s1 += '\0';
		s1 += "world";
		cout << s1 << endl;
		cout << s1.c_str() << endl;

		string s3("hello"), s4;
		cin >> s3 >> s4;
		cout << s3 << "---" << s4 << endl;
	}

	void DealUrl(const string& url)
	{
		size_t pos1 = url.find("://");
		if (pos1 == string::npos)
		{
			cout << "非法url" << endl;
			return;
		}
	
		string protocol = url.substr(0, pos1);
		cout << protocol << endl;

		size_t pos2 = url.find('/', pos1 + 3);
		if (pos2 == string::npos)
		{
			cout << "非法url" << endl;
			return;
		}
		string domain = url.substr(pos1 + 3, pos2 - pos1 - 3);
		cout << domain << endl;

		string uri = url.substr(pos2 + 1);
		cout << uri << endl << endl;
	}

	void test_string10()
	{
		string url1 = "https://cplusplus.com/reference/string/string/";
		string url2 = "https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=ascall&step_word=&hs=0&pn=0&spn=0&di=7108135681917976577&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=2613959014%2C543572025&os=2740573600%2C1059518451&simid=2613959014%2C543572025&adpicid=0&lpn=0&ln=179&fr=&fmq=1660115697093_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Fimg.php.cn%2Fupload%2Fimage%2F147%2F157%2F796%2F1593765739620093.png%26refer%3Dhttp%3A%2F%2Fimg.php.cn%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1662707704%26t%3Da68cb238bbb3f99d0554098c785d526e&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Brir_z%26e3BvgAzdH3FuwqAzdH3F9c9amd_z%26e3Bip4s&gsm=1&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwzLDIsNCw2LDEsNSw3LDgsOQ%3D%3D";
		string url3 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf";

		DealUrl(url1);
		DealUrl(url2);
		DealUrl(url3);
	}

	void test_string11()
	{
		string s1;
		s1.resize(20);

		string s2("hello");
		s2.resize(20, 'x');

		s2.resize(10);
	}
}
//Test.cpp
#include <iostream>
#include <string>
#include <list>
#include <assert.h>
using namespace std;

void test_string1()
{
	string s1;
	//string s2("hello world!!!");
	// string (const char* s);
	string s2 = "hello world!!!";
	cout << s1 << endl;
	cout << s2 << endl;

	string s3(s2);
	cout << s3 << endl;

	string s4(s2, 6, 5);
	cout << s4 << endl;

	// 第三个参数len大于后面字符长度,有多少拷贝多少拷贝到结尾
	string s5(s2, 6, 15);
	cout << s5 << endl;
	string s6(s2, 6);
	cout << s6 << endl;

	string s7("hello world", 5);
	cout << s7 << endl;

	string s8(100, 'x');
	cout << s8 << endl;

	//cin >> s1 >> s2;
	//cout << s1 << endl;
	//cout << s2 << endl;
}

void test_string2()
{
	string s1;
	string s2 = "hello world!!!"; // 构造+拷贝构造 -》优化 -- 直接构造

	s1 = s2;
	s1 = "xxxx"; // =
	s1 = 'y';
}

void test_string3()
{
	string s1("hello world");
	cout << s1[0] << endl;
	s1[0] = 'x';
	cout << s1[0] << endl;
	cout << s1 << endl;

	// 要求遍历string,每个字符+1
	for (size_t i = 0; i < s1.size(); ++i)
		//for (size_t i = 0; i < s1.length(); ++i)
	{
		s1[i]++;
	}
	cout << s1 << endl;

	const string s2("world");
	for (size_t i = 0; i < s2.size(); ++i)
	{
		//s2[i]++;
		cout << s2[i] << " ";
	}
	cout << endl;
	cout << s2 << endl;

	//s2[6];  内部会检查越界
}

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

	// 范围for -- 自动迭代,自动判断结束
	// 依次取s中每个字符,赋值给ch
	/*for (auto ch : s)
	{
		ch++;
		cout << ch << " ";
	}*/
	for (auto& ch : s)
	{
		ch++;
		cout << ch << " ";
	}
	cout << endl;

	cout << s << endl;

	list<int> lt(10, 1);
	list<int>::iterator lit = lt.begin();
	while (lit != lt.end())
	{
		cout << *lit << " ";
		++lit;
	}
	cout << endl;

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;

	// 范围for底层其实就是迭代器
}

void PrintString(const string& str)
{
	//string::const_iterator it = str.begin();
	auto it = str.begin();
	while (it != str.end())
	{
		//*it = 'x';
		cout << *it << " ";
		++it;
	}
	cout << endl;

	//auto rit = str.begin();
	string::const_reverse_iterator rit = str.rbegin();
	while (rit != str.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;
}

// iterator/const_iterator
// reverse_iterator/const_reverse_iterator

void test_string5()
{
	string s("hello");
	string::reverse_iterator rit = s.rbegin();
	while (rit != s.rend())
	{
		cout << *rit << " ";
		++rit;
	}
	cout << endl;

	PrintString(s);
}


void test_string6()
{
	string s("hello");
	s.push_back('-');
	s.push_back('-');
	s.append("world");
	cout << s << endl;

	string str("我来了");
	s += '@';
	s += str;
	s += "!!!";
	cout << s << endl;

	s.append(++str.begin(), --str.end());
	cout << s << endl;

	//string copy(++s.begin(), --s.end());
	string copy(s.begin() + 5, s.end() - 5);
	cout << copy << endl;
}

void test_string7()
{
	/*string s1;
	string s2("11111111111111");
	cout << s1.max_size() << endl;
	cout << s2.max_size() << endl;

	cout << s2.capacity() << endl;
	cout << s2.capacity() << endl;*/

	string s;
	// reverse 逆置
	s.reserve(1000); //保留 开空间
	//s.resize(1000, 'x');    //     开空间 + 初始化
	size_t sz = s.capacity();
	sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 1000; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

void test_string8()
{
	string str("wo lai le");
	/*for (size_t i = 0; i < str.size();)
	{
		if (str[i] == ' ')
		{
			str.insert(i, "20%");
			i += 4;
		}
		else
		{
			++i;
		}
	}
	cout << str << endl;*/

	/*for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		{
			str.insert(i, "20%");
			i += 3;
		}
	}
	cout << str << endl;

	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		{
			str.erase(i, 1);
		}
	}
	cout << str << endl;*/

	string newstr;
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] != ' ')
		{
			newstr += str[i];
		}
		else
		{
			newstr += "20%";
		}
	}
	cout << newstr << endl;
}

void test_string9()
{
	string filename("test.cpp");
	cout << filename << endl;
	cout << filename.c_str() << endl;

	FILE* fout = fopen(filename.c_str(), "r");
	assert(fout);
	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}
}

void test_string10()
{
	string filename("test.cpp");
	cout << filename << endl;
	cout << filename.c_str() << endl;

	filename += '\0';
	filename += "string.cpp";
	cout << filename << endl; // string 对象size为准
	cout << filename.c_str() << endl; // 常量字符串对象\0

	cout << filename.size() << endl;
	string copy = filename;
	cout << copy << endl << endl;

	for (unsigned char ch = 0; ch < 128; ++ch)
	{
		cout << ch;
	}
	cout << endl;
	cout << "\\0" << endl;
}

void DealUrl(const string& url)
{
	size_t pos1 = url.find("://");
	if (pos1 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}

	string protocol = url.substr(0, pos1);
	cout << protocol << endl;

	size_t pos2 = url.find('/', pos1 + 3);
	if (pos2 == string::npos)
	{
		cout << "非法url" << endl;
		return;
	}
	string domain = url.substr(pos1 + 3, pos2 - pos1 - 3);
	cout << domain << endl;

	string uri = url.substr(pos2 + 1);
	cout << uri << endl << endl;
}

void test_string11()
{
	string filename("test.cpp.tar.zip");
	// 后缀
	//size_t pos = filename.find('.');
	size_t pos = filename.rfind('.');
	if (pos != string::npos)
	{
		//string suff = filename.substr(pos, filename.size() - pos);
		string suff = filename.substr(pos);

		cout << suff << endl;
	}

	string url1 = "https://cplusplus.com/reference/string/string/";
	string url2 = "https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=ascall&step_word=&hs=0&pn=0&spn=0&di=7108135681917976577&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=2613959014%2C543572025&os=2740573600%2C1059518451&simid=2613959014%2C543572025&adpicid=0&lpn=0&ln=179&fr=&fmq=1660115697093_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%3A%2F%2Fimg.php.cn%2Fupload%2Fimage%2F147%2F157%2F796%2F1593765739620093.png%26refer%3Dhttp%3A%2F%2Fimg.php.cn%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1662707704%26t%3Da68cb238bbb3f99d0554098c785d526e&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Brir_z%26e3BvgAzdH3FuwqAzdH3F9c9amd_z%26e3Bip4s&gsm=1&rpstart=0&rpnum=0&islist=&querylist=&nojc=undefined&dyTabStr=MCwzLDIsNCw2LDEsNSw3LDgsOQ%3D%3D";
	string url3 = "ftp://ftp.cs.umd.edu/pub/skipLists/skiplists.pdf";

	DealUrl(url1);
	DealUrl(url2);
	DealUrl(url3);
}

void test_string12()
{
	int ival;
	double dval;
	cin >> ival >> dval;
	string istr = to_string(ival);
	string dstr = to_string(dval);
	cout << istr << endl;
	cout << dstr << endl;

	istr = "9999";
	dstr = "9999.99";
	ival = stoi(istr);
	dval = stod(dstr);
}

void test_string13()
{
	string s0;
	string s1("111111");
	string s2("11111111111111111111111111111111111111111");
	cout << sizeof(s1) << endl;
	cout << sizeof(s2) << endl;
}

#include "string.h"

int main()
{
	try
	{
		//bit::test_string11();
		test_string13();
	}
	catch (const exception& e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

 4.练习题

      1.给你一个字符串 s ,根据下述规则反转字符串:1.所有非英文字母保留在原有位置;2.所有英文字母(小写或大写)位置反转。返回反转后的 s 。

class Solution
{
public:
	bool IsLetter(char ch)
	{
		if ((ch >= 'a' && ch <= 'z') ||
			(ch >= 'A' && ch <= 'Z'))
			return true;
		else
			return false;
	}
	string reverseOnlyLetters(string s)
	{
		size_t begin = 0, end = s.size() - 1;
		while (begin < end)
		{
			while (begin < end && !IsLetter(s[begin]))
				++begin;

			while (begin < end && !IsLetter(s[end]))
				--end;

			swap(s[begin], s[end]);
			++begin;
			--end;
		}

		return s;

	}
};

     2.给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。

class Solution {
public:
	string addStrings(string num1, string num2) {
		int end1 = num1.size() - 1, end2 = num2.size() - 1;
		int next = 0;
		string strRet;
		while (end1 >= 0 || end2 >= 0)
		{
			int val1 = end1 >= 0 ? num1[end1] - '0' : 0;
			int val2 = end2 >= 0 ? num2[end2] - '0' : 0;
			int ret = val1 + val2 + next;
			next = ret > 9 ? 1 : 0;

			//头插
			//strRet.insert(0,1,'0'+(ret%10));
		   // strRet.insert(strRet.begin(),'0'+(ret%10));

		   //尾插
			strRet += ('0' + ret % 10);

			--end1;
			--end2;
		}

		if (next == 1)
			strRet += '1';

		//逆置
		reverse(strRet.begin(), strRet.end());

		return strRet;

	}
};

     3.计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾) 

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
   // cin>>str;
    getline(cin,str);
    size_t pos=str.rfind(' ');
    if(pos!=string::npos)
    {
        cout<<str.size()-pos-1<<endl;
    }
    else
    {
        cout<<str.size()<<endl;
    }
      
}

     4.给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回-1 。

class Solution {
public:
    int firstUniqChar(string s) {
        int countArr[26]={0};
        for(auto ch:s)
        {
            countArr[ch-'a']++;
        }

        for(size_t i=0;i<s.size();i++)
        {
            if(countArr[s[i]-'a']==1)
            return i;
        }

        return -1;

    }
};

     5.如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个回文串。

class Solution
{
public:
	bool isLetterOrNumber(char ch)
	{
		return (ch >= '0' && ch <= '9')
			|| (ch >= 'a' && ch <= 'z')
			|| (ch >= 'A' && ch <= 'Z');
	}

	bool isPalindrome(string s) 
	{
		// 先小写字母转换成大写,再进行判断
		for (auto& ch : s)
		{
			if (ch >= 'a' && ch <= 'z')
				ch -= 32;
		}

		int begin = 0, end = s.size() - 1;
		while (begin < end)
		{
			while (begin < end && !isLetterOrNumber(s[begin]))
				++begin;

			while (begin < end && !isLetterOrNumber(s[end]))
				--end;

			if (s[begin] != s[end])
			{
				return false;
			}
			else
			{

				++begin;
				--end;
			}
		}

		return true;
	}
};

5.string类的模拟实现

5.1 浅拷贝

     浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来 。如果 对象中管理资源 ,最后就会 导致多个对象共 享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为 还有效,所以当继续对资源进项操作时,就会发生发生了访问违规

5.2 深拷贝

     如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。

5.3 写时拷贝

       写时拷贝就是一种拖延症,是在浅拷贝的基础之上增加了引用计数的方式来实现的。
       引用计数:用来记录资源使用者的个数。在构造时,将资源的计数给成 1 ,每增加一个对象使用该资源,就给计数增加1 ,当某个对象被销毁时,先给该计数减 1 ,然后再检查是否需要释放资源,如果计数为 1 ,说明该对象时资源的最后一个使用者,将该资源释放;否则就不能释放,因为还有其他对象在使用该资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值