C++初阶:string类

为什么学习string类?

C语言中的字符串

C 语言中,字符串是以 '\0' 结尾的一些字符的集合,为了操作方便, C 标准库中提供了一些 str 系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP 的思想,而且底层空间需要用户自
己管理,稍不留神可能还会越界访问。
OJ 中,有关字符串的题目基本以 string 类的形式出现,而且在常规工作中,为了简单、方便、快捷,基本都使用string 类,很少有人去使用 C 库中的字符串操作函数。

标准库中的string

string(了解)

小知识:string类是在STL之前设计出来的,设计的接口有些冗余。

string类的文档介绍

  1. 字符串是表示字符序列的类
2. 标准的字符串类提供了对此类对象的支持,其接口类似于标准字符容器的接口,但添加了专门用于操作单字节字符字符串的设计特性。
3. string 类是使用 char( 即作为它的字符类型,使用它的默认 char_traits 和分配器类型 ( 关于模板的更多信息,请参阅basic_string)
4. string 类是 basic_string 模板类的一个实例,它使用 char 来实例化 basic_string 模板类,并用 char_traits和allocator 作为 basic_string 的默认参数 ( 根于更多的模板信息请参考 basic_string)
5. 注意,这个类独立于所使用的编码来处理字节 : 如果用来处理多字节或变长字符 ( UTF-8) 的序列,这个类的所有成员( 如长度或大小 ) 以及它的迭代器,将仍然按照字节 ( 而不是实际编码的字符 ) 来操作。
总结:
1. string 是表示字符串的字符串类
2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作 string 的常规操作。
3. string 在底层实际是: basic_string 模板类的别名, typedef basic_string<char, char_traits, allocator>string;
4. 不能操作多字节或者变长字符的序列。
使用 string 类时,必须包含 #include<string> 以及 using namespace std ;

string类的常用接口说明

1.string类对象的常见构造和赋值

constructor(构造和拷贝构造)函数

operator=函数

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s0;
	string s1("hello world");
	string s2(s1);
	string s3(s1, 5, 3);
	string s4(s1, 5, 10);
	string s5(s1, 5);
	string s6(10, '#');

	cout << s0 << endl;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	cout << s5 << endl;
    cout << s6 << endl;

    s0 = s6;
	cout << s0 << endl;
	return 0;
}

2. string类对象的容量操作

string::size - C++ 参考 (cplusplus.com)  返回字符串有效字符长度

string::length - C++ 参考 (cplusplus.com)  返回字符串有效字符长度(主要针对string类)

string::max_size - C++参考 (cplusplus.com)  返回字符串的最大大小

string::capacity - C++ 参考 (cplusplus.com)   返回空间总大小 。不同系统的扩容机制不同(vs下1.5倍扩容,g++下2倍扩容)

string::clear - C++ 参考 (cplusplus.com) 清空有效字符,但不改变空间,即空间总大小不变

string::empty - C++ 参考 (cplusplus.com) 测试字符串是否为空

void test_string4()
{
	string s1("hello world");
	cout << s1.size() << endl;
	cout << s1.length() << endl;

	cout << s1.max_size() << endl;
	cout << s1.capacity() << endl;

	// 查看扩容机制
	string s;

	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';
	cout << "making s grow:\n";
	for (int i = 0; i < 100; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}

	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;


	s1.clear();
	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;
}
int main()
{
	test_string4();
	return 0;
}


string::shrink_to_fit - C++参考 (cplusplus.com) 缩容。C++ 标准库的规定,对于 shrink_to_fit 方法,并不保证一定会收缩容量,具体是否收缩取决于标准库的实现。

void test_string4()
{
	string s1("hello worldxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

	cout << s1.capacity() << endl;
	cout << s1.size() << endl;

	s1.clear();
	cout << s1 << endl;
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;

	// 缩容
	s1.shrink_to_fit();
	cout << s1.capacity() << endl;
	cout << s1.size() << endl;
}
int main()
{
	test_string4();
	return 0;
}

string::reserve - C++ 参考 (cplusplus.com)  为字符串预留空间,生成的字符串容量可能等于或大于n (不同平台下实现机制不一样)

void test_string5()
{
	string s1("hello worldxxxxxx");
	cout << s1.size() << endl;
	cout << s1.capacity() << endl<<endl;

	// 比当前capacity大才会扩容
	s1.reserve(200);
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
}
int main()
{
	test_string5();
	return 0;
}

string::resize - C++ 参考 (cplusplus.com) 调整字符串大小

void test_string5()
{
	string s2("hello worldxxxxxx");
	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(10);

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(20);

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;

	s2.resize(100, 'x');

	cout << s2.size() << endl;
	cout << s2.capacity() << endl << endl;
}
int main()
{
	test_string5();
	return 0;
}

string::at - C++ 参考 (cplusplus.com)

void test_string6()
{
	string s1("xhello world");
	cout << s1[5] << endl;
	cout << s1.at(5) << endl;

	//对于越界访问的检查不同
	s1[15];
	s1.at(15);
}
int main()
{
	test_string6();
	return 0;
}
注意:
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[](访问使用连续的内存空间来存储元素,如数组,顺序表)

// a[i] 等价于 *(a+i)
void test_string2()
{
	string s1("hello world");

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

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

	string s3("hello world");//可读可写
	s3[0]++;
	cout << s3 << endl;

	const string s2("hello world");//只读
	//s2[0]++;
	cout << s2 << endl;
}
int main()
{
	test_string2();
	return 0;
}

begin+end:左闭右开区间  [  )   

迭代器行为像指针一样的类型对象

(迭代器是访问的主流选择,通用)

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

	it3 = s3.begin();
	while (it3 != s3.end())
	{
		cout << *it3 << " ";
		++it3;
	}
	cout << endl;
}
int main()
{
	test_string2();
	return 0;
}

范围for

void test_string2()
{
	string s3("hello world");
	// 底层就是迭代器
	for (auto e : s3)
	{
		cout << e << " ";
	}
	cout << endl;
}
int main()
{
	test_string2();
	return 0;
}

rbegin+rend: 左开右闭区间  (  ]

反向迭代器

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

	// 可读可写
	string::reverse_iterator it2 = s1.rbegin();
	while (it2 != s1.rend())
	{
		*it2 += 3;
		
		cout << *it2 << " ";
		++it2;
	}
	cout << endl;

	// 只读
	const string s3("hello world");
	string::const_reverse_iterator it3 = s3.rbegin();
	while (it3 != s3.rend())
	{
		// *it3 += 3;

		cout << *it3 << " ";
		++it3;
	}
	cout << endl;

}
int main()
{
	test_string3();
	return 0;
}

   

4. string类对象的修改操作

push_back  在字符串后尾插字符c

string::append - C++ 参考 (cplusplus.com)  在字符串后追加一个字符串

string::operator+= - C++ 参考 (cplusplus.com)  在字符串后追加字符串str(常用)

void test_string7()
{
	string s1("xhello world");
	s1.push_back('!');
	cout << s1 << endl;

	s1.append("hello bit");
	cout << s1 << endl;

	s1.append(10, 'x');
	cout << s1 << endl;

	string s2("  apple ");
	//s1.append(s2);
	//cout << s1 << endl;
	s1.append(++s2.begin(), --s2.end());
	cout << s1 << endl;

	string s3("hello world");
	s3 += ' ';
	s3 += "apple";
	cout << s3 << endl;
}



string::assign - C++ 参考 (cplusplus.com)  为字符串分配一个新值,替换其当前内容。

string::insert - C++ 参考 (cplusplus.com)  在字符串中插入其他字符, pos(或 p)指示的字符位置之前。

string::erase - C++ 参考 (cplusplus.com)  从字符串中删除字符

string::replace - C++ 参考 (cplusplus.com) 替换字符串部分

void test_string8()
{
	string s1("xhello world");
	cout << s1 << endl;

	s1.assign(" xxxxx");
	cout << s1 << endl;

	s1.insert(0, "yyyy");
	cout << s1 << endl;

	s1.erase(5, 3);
	cout << s1 << endl;

	s1.erase();
	cout << s1 << endl;

	string s2("hello world hello bit");
	//s2.replace(5, 1, "20%");
	//cout << s2 << endl;

	size_t pos = s2.find(' ');
	while (pos != string::npos)
	{
		s2.replace(pos, 1, "20%");
		pos = s2.find(' ');
	}
	cout << s2 << endl;
}

int main()
{
	test_string8();
	return 0;
}

	// insert/erase/replace
	// 能少用就要少用,因为基本都要挪动数据,效率不高

string::c_str - C++参考 (cplusplus.com)   返回 C 格式字符串
void test_string9()
{
	string s1("hello world");

	string filename("test.cpp");
	FILE* fout = fopen(filename.c_str(), "r");
}

string::find - C++ 参考 (cplusplus.com) 从字符串pos位置开始往后找字符c或字符串,返回该字符在字符串中的位置

string::rfind - C++ 参考 (cplusplus.com) 从字符串pos位置开始往前找字符c或字符串,返回该字符在字符串中的位置

string::substr - C++ 参考 (cplusplus.com) str中从pos位置开始,截取n个字符,然后将其返回

string::npos - C++ 参考 (cplusplus.com)  size_t的最大值

string::find_first_of - C++参考 (cplusplus.com) 在字符串中搜索与其参数中指定的任何字符匹配的第一个字符。

string::find_last_of - C++参考 (cplusplus.com)  在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。

//[0, 9]  
//[0, 10)  左闭右开,右-左是个数
void test_string10()
{
	//string s1("file.cpp");
	string s1("file.c.tar.zip");

	// 拿到文件的后缀
	size_t pos1 = s1.rfind('.');
	if (pos1 != string::npos)
	{
		string suffix = s1.substr(pos1);
		//string suffix = s1.substr(pos1, s1.size()-pos1);

		cout << suffix << endl;
	}
	else
	{
		cout << "没有后缀" << endl;
	}

	string url1("https://legacy.cplusplus.com/reference/string/string/substr/");

	string protocol, domain, uri;
	size_t i1 = url1.find(':');
	if (i1 != string::npos)
	{
		protocol = url1.substr(0, i1 - 0);
		cout << protocol << endl;
	}

	// strchar
	size_t i2 = url1.find('/', i1 + 3);
	if (i2 != string::npos)
	{
		domain = url1.substr(i1 + 3, i2 - (i1 + 3));
		cout << domain << endl;

		uri = url1.substr(i2 + 1);
		cout << uri << endl;
	}
	
    cout << endl;

	std::string str("Please, replace the vowels in this sentence by asterisks.");
	cout << str << endl;

	// strtok
	std::size_t found = str.find_first_of("aeiou");
	while (found != std::string::npos)
	{
		str[found] = '*';
		found = str.find_first_of("aeiou", found + 1);
	}
	cout << str << endl;
}
int main()
{
	test_string10();
    return 0;
}

注意:
1. string 尾部追加字符时, s.push_back(c) / s.append(1, c) / s += 'c' 三种的实现方式差不多,一般
情况下 string 类的 += 操作用的比较多, += 操作不仅可以连接单个字符,还可以连接字符串。
2. string 操作时,如果能够大概预估到放多少字符,可以先通过 reserve 把空间预留好。

5. string类非成员函数

operator+ (string) - C++ 参考 (cplusplus.com) 尽量少用,因为传值返回,导致深拷贝效率低

关系运算符(字符串) - C++ 参考 (cplusplus.com)  大小比较

operator>> (string) - C++参考 (cplusplus.com)  输入运算符重载

operator<< (string) - C++参考 (cplusplus.com)  输出运算符重载

getline (string) - C++ 参考 (cplusplus.com)  获取一行字符串,遇到 ' \n' 结束;也可以自定义结束符。

void test_string10()
{
	string ss1 = "xxx";
	string ss2 = "yyy";

	string ret = ss1 + ss2;
	cout << ret << endl;

	cout << (ss1 < ss2) << endl;

	string ret1 = ss1 + "yyyy";
	string ret2 = "yyyy" + ss2;
}
int main()
{
	test_string10();
    return 0;
}

字符串转换

to_string - C++ Reference (cplusplus.com)  将数值转换为字符串

stoi - C++ 参考 (cplusplus.com)  将字符串转换为整数

stod - C++ 参考 (cplusplus.com)  将字符串转换为双精度

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
using namespace std;

int main()
{
	int i = 1234;
	double d = 11.22;
	string s1 = to_string(i);
	string s2 = to_string(d);

	string s3("45.55");
	double d3 = stod(s3);

	cout << d3;

	return 0;
}

浅拷贝

浅拷贝:也称位拷贝,编译器只是将对象中的值拷贝过来 。如果 对象中管理资源 ,最后就会 导致多个对象共 享同一份资源,当一个对象销毁时就会将该资源释放掉,而此时另一些对象不知道该资源已经被释放,以为 还有效,所以当继续对资源进项操作时,就会发生发生了访问违规
就像一个家庭中有两个孩子,但父母只买了一份玩具,两个孩子愿意一块玩,则万事大吉,万一不想分享就你争我夺,玩具损坏。

深拷贝

可以采用深拷贝解决浅拷贝问题,即: 每个对象都有一份独立的资源,不要和其他对象共享 。父母给每个孩子都买一份玩具,各自玩各自的就不会有问题了。
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。

写时拷贝(了解)

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

vsg++string结构的说明 (了解即可)

注意:下述结构是在 32 位平台下进行验证, 32 位平台下指针占 4 个字节。
vs string 的结构
string 总共占 28(16+12) 个字节 ,内部结构稍微复杂一点,先是 有一个联合体,联合体用来定义 string 中字
符串的存储空间
        当字符串长度小于16 时,使用内部固定的字符数组来存放
        当字符串长度大于等于16 时,从堆上开辟空间
union _Bxty
{ // storage for small buffer or pointer to larger one
 value_type _Buf[_BUF_SIZE];
 pointer _Ptr;
 char _Alias[_BUF_SIZE]; // to permit aliasing
} _Bx;
这种设计也是有一定道理的,大多数情况下字符串的长度都小于 16 ,那 string 对象创建好之后,内
部已经有了 16 个字符数组的固定空间,不需要通过堆创建,效率高。
其次:还有 一个 size_t 字段保存字符串长度,一个 size_t 字段保存从堆上开辟空间总的容量
最后:还 有一个指针 做一些其他事情。
故总共占 16+4+4+4=28 个字节。
g++ string 的结构
G++ 下, string 是通过写时拷贝实现的, string 对象总共占 4 个字节,内部只包含了一个指针(结构指针),该指针将来指向一块堆空间,内部包含了如下字段:
空间总大小
字符串有效长度
引用计数
struct _Rep_base
{
 size_type _M_length;
 size_type _M_capacity;
 _Atomic_word _M_refcount;
};
指向堆空间的指针,用来存储字符串
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值