STL常用容器之 string

本文详细介绍了C++ STL中的string容器,包括其基本概念、构造函数、赋值操作、字符串拼接、查找与替换、字符串比较、字符存取、插入与删除以及子串操作。string作为字符串类,提供了丰富的内置方法,方便对字符串进行安全高效的管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

STL常用容器之 string

1. string容器

1. string的基本概念

本质:string是C++风格的字符串,而string本质上是一个类

string 和char 区别*:

  • char* 是一个指针
  • string是一个类,类内部封装了char *,管理这个字符串,是char *型的容器

特点:string类内封装了很多成员的方法

例如: 查找find,拷贝copy,删除delete,替换replace,插入insert

steing管理char *所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责

2. string构造函数

构造函数原型:

  • string();//创建一个空的字符串 例:string str;
  • string(const char* s); //使用字符串初始化
  • string(const string & str);//使用一个string对象初始化另一个string对象
  • string(int n, char c);//使用n个字符c初始化

例:

#include <iostream>
#include <string>
using namespace std;
void test()
{
    // string();
	string s1;//默认构造
	const char* str = "hello world";
	// string(const char* s);
    string s2(str);
	cout << s2 << endl; 
	//string(const string & str);
	string s3(s2);
	cout << s3 << endl;
	//* string(int n, char c);
	string s4(10,'a');
	cout << s4 << endl;
}
int main()
{
	test();
	 
	system("pause");
	
	return 0;	
} 

3. string赋值操作

赋值的函数原型:

  1. string& operator=(const char* s); //char*类型字符串 赋值给当前字符串

  2. string& operator=(const string &s);//字符串s赋值给当前字符串

  3. string& operator=(char c);//字符赋值给当前字符串

  4. string& assign(const char* s);//把字符串s赋给当前字符串

  5. string& assign(const char *s,int n);//把字符串s的前n个字符赋给当前字符串

  6. string& assign(const string &s);//把字符串s赋给当前字符串

  7. string& assign(int n, char c);//把n个字符c赋给当前字符串

例:

#include <iostream>
#include <string>
using namespace std;
void test()
{
	//string& operator=(const char* s);
	string s1;
	s1 = "hello world";
	cout << s1 << endl; 
	//string& operator=(const string &s);
	string s2;
	s2 = s1;
	cout << s2 << endl;
	//string& operator=(char c);
	string s3;
	s3 = 'aaa';
	cout << s3 << endl;
	//string& assign(const char* s);
	string s4;
	s4.assign("hello C++");
	cout << s4 << endl;
	//string& assign(const char *s,int n);
	string s5;
	s5.assign("hello C++",5);
	cout << s5 << endl;
	//string& assign(const string &s);
	string s6;
	s6.assign(s4);
	cout << s6 << endl; 
	//string& assign(int n, char c);
	string s7;
	s7.assign(3,'a');
	cout << s7 << endl;
}
int main()
{
	test();
	 
	system("pause");
	
	return 0;	
}  

4. string字符串拼接

函数原型

  1. string& operator+=(const char* str);//重载+=
  2. string& operator+=(const char c);//重载+=
  3. string& operator+=(const string& str);//重载+=
  4. string& append(const char *s);//把字符串s连接到当前字符串结尾
  5. string& append(const char *s, int n);//把字符串s的前n个字符连接到当前字符串结尾
  6. string& append(const string& s);//同operator+=(const string& str)
  7. string& append(const string &s, int pos, int n);//字符串s中从pos开始的n个字符连接到字符串结尾

例:

#include <iostream>
#include <string>
using namespace std;
/*
1. `string& operator+=(const char* str);//重载+=`
2. `string& operator+=(const char c);//重载+=`
3. `string& operator+=(const string& str);//重载+=`
4. `string& append(const char *s);//把字符串s连接到当前字符串结尾`
5. `string& append(const char *s, int n);//把字符串s的前n个字符连接到当前字符串结尾`
6. `string& append(const string& s);//同operator+=(const string& str)`
7. `string& append(const string &s, int pos, int n);//字符串s中从pos开始的n个字符连接到字符串结尾`
*/ 
void test()
{
	//string& operator+=(const char* str);
	string s1 = "我";
	s1 += "爱玩游戏";
	cout << s1 << endl; 
	//string& operator+=(const char c);
	s1 += ':';
	cout << s1 << endl;
	//string& operator+=(const string& str);
	string s2 = "LOL游戏";
	s1 += s2;
	cout << s1 << endl;
	
	// string& append(const char *s);
	string s3 = "I";
	s3.append(" Love ");
	cout << s3 << endl;
	
	//string& append(const char *s, int n);
	s3.append("you sa",3);
	cout << s3 << endl;
	
	// string& append(const string& s);
	string s4;
	s4.append(s3);
	cout << s4 << endl;
	//string& append(const string &s, int pos, int n);
	s4.append(s4,1,5);
	cout << s4 << endl;
}

int main()
{
	test();
	 
	system("pause");
	
	return 0;	
} 
 

5. string查找和替换

查找:查找指定字符串是否存在

  1. int find(const string& str, int pos = 0) const;//查找str第一次出现位置,从pos开始查找
  2. int find(const char* s, int pos = 0) const;//查找s第一次出现的位置,从pos开始查找
  3. int find(const char* s, int pos, int n) const;//从pos位置查找s的前n个字符第一次位置
  4. int find(const char c, int pos = 0) const;//查找字符c第一次出现位置
  5. int rfind(const string& str, int pos = npos) const;//查找str最后依次位置,从pos开始查找
  6. int rfind(const* s,int pos = npos) const;//查找s最后一次出现位置,从pos开始
  7. int rfind(const char* s, int pos, int n) const;//从pos查找s的前n个字符最后一次位置
  8. int rfind(const char c, int pos = 0) const;//查找字符c最后一次出现位置

替换:在指定位置替换字符串

  1. string& replace(int pos, int n,const string& str);//替换从pos开始n个字符为字符串str
  2. string& replace(int pos, int n, const char* s);//替换pos开始的n个字符为字符串s

6. string字符串比较

函数原型:

  1. int compare(const string &s) const;//与字符串s比较
  2. int compare(const char* s) const;//与字符串s比较

比较方式:按字符的ASCII进行比较

  • 相等 返回 0
  • 大于 返回 1
  • 小于 返回 -1

7. string字符存取

string中单个字符获取的方式:

  1. char& operator[](int n);//通过[]方式获取字符
  2. char& at(int n);//通过at方法获取字符

例:

#include <iostream>
#include <string>
using namespace std;
 
void test()
{
	string s = "hello";
	//1. 通过[]访问单个字符 
	for(int i = 0; i < s.size(); i++)
	{
		cout << s[i] << " ";	
	} 
	cout << endl;
	//2. 通过at访问 
	for(int i = 0; i < s.size(); i++)
	{
		cout << s.at(i) << " ";	
	} 
	cout << endl;
	
	//修改 
	s[0] = 'x';
	s.at(1) = 'x';
	//变为xxllo  
	cout << s << endl; 
}

int main()
{
	test();
	 
	system("pause");
	
	return 0;	
} 
 

8. string插入和删除

函数原型:

  1. string& insert(int pos, const char* s);//插入字符串
  2. string& insert(int pos, const string& str);//插入字符串
  3. string& insert(int pos, int n, char c);//指定位置插入n个字符c
  4. string& erase(int pos, int n = npos);//删除从pos开始的n个字符

例:

void test()
{
	string s = "hello";
 	//插入
	 s.insert(1,"111");
	 cout << s << endl;
	 
	//删除
	s.erase(1,3);
	cout << s << endl; 
}

9. string子串

函数原型:

  • string substr(int pos = 0, int n = npos) const;//返回由pos开始的n个字符组成的字符串

例:

void test()
{
	string s = "abcde";
 	//取子串
	string subStr = s.substr(1,3);
	cout << subStr << endl; 
}
### C++ STL String常用方法总结 以下是关于 `std::string` 的一些常见操作及其功能说明: #### 1. 构造字符串对象 可以通过多种方式创建 `std::string` 对象,例如默认构造、初始化列表或者拷贝构造等方式[^3]。 ```cpp #include <iostream> #include <string> int main() { std::string str1; // 默认构造 std::string str2("hello world");// 初始化为指定字符序列 std::cout << str1 << std::endl; std::cout << str2 << std::endl; return 0; } ``` #### 2. 字符串大小与容量 可以使用成员函数获取字符串长度以及调整其容量。 - **size()**: 返回当前存储的字符数。 - **length()**: 同 size(), 表示有效字符数量。 - **capacity()**: 获取分配的空间大小。 - **resize(n)**: 调整字符串的有效长度至 n。 - **reserve(n)**: 预留至少能容纳 n 个字符的空间。 ```cpp #include <iostream> #include <string> int main() { std::string s = "abcdef"; std::cout << "Size: " << s.size() << ", Capacity: " << s.capacity() << std::endl; s.resize(10, 'z'); // 扩展到 10 个字符并填充 'z' std::cout << "Resized: " << s << std::endl; s.reserve(50); // 提前预留空间 std::cout << "Capacity after reserve: " << s.capacity() << std::endl; return 0; } ``` #### 3. 修改字符串内容 提供了一系列用于修改字符串的方法,比如替换子串、追加新数据等。 - **append(str)** 或者运算符 += : 将另一个字符串附加到现有字符串后面。 - **insert(pos, str)**: 插入一段新的文本到特定位置 pos 处。 - **erase(start_pos, num_chars)**: 删除从 start_pos 开始的 num_chars 个字符。 - **replace(start_pos, num_chars, new_str)**: 替代部分区域的内容。 ```cpp #include <iostream> #include <string> int main() { std::string s = "Hello"; s.append(", World!"); // 添加额外的部分 std::cout << s << std::endl; s.insert(5, " there"); // 在索引 5 处插入文字 std::cout << s << std::endl; s.erase(5, 6); // 移除中间的一段话 std::cout << s << std::endl; s.replace(6, 7, "Universe"); // 更改某些词语 std::cout << s << std::endl; return 0; } ``` #### 4. 查找和比较 支持查找某个子串的位置以及执行各种形式的对比测试。 - **find(substr)** 和 **rfind(substr)**: 寻找第一次/最后一次出现 substr 的地方;如果找不到则返回 `std::string::npos`. - **compare(otherStr)**: 判断两个字符串之间的字典序关系 (-1表示小于,0相等,+1大于). ```cpp #include <iostream> #include <string> int main() { std::string s = "This is a sample sentence."; auto idx = s.find("sample"); if (idx != std::string::npos){ std::cout << "'sample' found at index: " << idx << std::endl; } bool isEqual = !s.compare("Another string."); std::cout << "Strings are equal? " << isEqual << std::endl; return 0; } ``` #### 5. 字母转换及其他辅助工具 还包含了针对单个字母的操作手段,如转成大写或小写字母等功能[^1]. - **tolower(c)/toupper(c)**: 把给定字符 c 变更为对应的小写 / 大写版本. ```cpp #include <iostream> #include <string> #include <cctype> int main(){ std::string s="ABCDEFG"; for(int i=0;i<s.size();i++) { s[i]=static_cast<char>(tolower(static_cast<unsigned char>(s[i]))); } std::cout<<s<<std::endl; return 0; } ``` 通过上述这些基本技巧的应用,能够极大简化日常开发中的字符串处理工作量。同时得益于标准模板库的强大特性,开发者无需手动管理内存即可轻松实现复杂逻辑[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值