【C++】——string类

前言

在C语言里面我们用的字符串都是以'\0'结尾的字符合集,为了操作方便所以在c++中推出了stirng类

string介绍

1.string是表示字符串的字符串类

2.因为是类,所以他会有一些常用的接口,同时也添加了专门用来操作string的常规操作

3.string在底层实际是:basic_string模板类的别名。也就是说string是一个模板,之所以要设置为模板是为了适应更多的编码

4.不能操作多字节或者变长字符的序列

🎈string常用接口说明

1.string类对象的构造函数

void Teststring()
{
	string str1;//构造空的
	string str2("hello,world");//string str2="hello,world";//常量字符串构造
	string str3(str2);//用对象构造
}

 2.string类对象的容量操作

void Teststring()
{
	string str("hello,world");
	cout << "有效字符:" << str.size() << endl << endl;//cout << str.length() << endl;
	cout << "容量大小:" << str.capacity() << endl << endl;
	cout << "是否为空?" << str.empty() << endl << endl;;
	cout << "清空有效字符"  << endl;
	str.clear();
	cout << "现在有效字符:" << str.size() << endl << endl;
	cout << "为字符串预留空间:"  << endl;
	str.reserve(20);
	cout << "当前容量大小" << str.capacity() << endl << endl;;
	cout << "有效字符变为n"  << endl;
	str.resize(16, 'a');
	cout << "当前有效字符:" << str.size() << endl;

}

 

这里要注意两个点

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


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

 

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

1.使用下标运算符
	string s = "Hello world!";
	cout << s[0] << endl;
	cout << s[s.size() - 1] << endl;

	cout << s << endl;
	s[0] = 'h';
	cout << s << endl;

也可以用来遍历数组

	for (int i = 0; i < s.size(); i++)
	{
		cout << s[i] << " ";
	}

 

2.使用迭代器 
for (auto i = s.begin(); i < end(); i++)
	{
		cout << *i << " ";
	}

这个是正向的,当然还有反向的

 

for (auto i = s.rbegin(); i < s.rend(); i++)
	{
		cout << *i << " ";
	}

 

 

 3.使用基于范围的f基于范围的for语句是C++11新提供的一种语句,其语法形式是:
在这里插入图片描述or语句

declaration:定义一个变量,它每次的值都是expression中的基础元素
expression:一个已经定义的对象(变量)
statement:具体的语句

 如果不是很理解,那就看代码理解

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

这里就相当于是把s的一个字符依次给e,然后我们打印e就是在打印s的每一个字符,当然也可以写成引用,写成引用就可以修改s里面的字符了

4.string类对象的修改操作

 1.push_back

string s("hello,world");
	s.push_back('a');
	cout << s;

2.append

string s("i love China!");
s.append("forever");//执行完后,s=” i love China! forever”

3.operator+=

虽然和append类似,但是它可以加string对象,但是append不行

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	string s("hello,world");
	string str("love,you");
	s.append("asdasd");
	cout << s << endl;
	s += "dsadx";
	cout << s << endl;
	s += str;
	cout << s << endl;
	return 0;
}


4.c_str 

int main()
{
	string s("hello,world");
	cout << s.c_str() << endl;
	return 0;
}

 

5.find()

 find的参数形式有很多,下面一一列举来看看

int main()
{
	string str("There are two needles in this haystack with needles.");
	string str2("needle");
	//1.对应参数为str,pos
	size_t found = str.find(str2);//返回第一个"needles"n的下标
	if (found != string::npos)
		cout << "first 'needle' found at: " << found << '\n';
	//2.对应参数为s,pos, n
	found = str.find("needles are small", found + 1, 6);
	if (found != std::string::npos)
		cout << "second 'needle' found at: " << found << '\n';
	//3.对应参数为s,pos
	found = str.find("haystack");
	if (found != std::string::npos)
		cout << "'haystack' also found at: " << found << '\n';
	//4.对应参数args为c,pos
	found = str.find('.');
	if (found != string::npos)//npos在string中定义
		cout << "Period found at: " << found << '\n';

	return 0;
}

 

6.rfind()

就是从后往前找

cout << " rfind()函数:" << endl;
string str("The sixth sick sheik's sixth sheep's sick.");
string key("sixth");

size_t found = str.rfind(key);//找到最后一个sixth的下标
if (found != string::npos)
	str.replace(found, key.length(), "seventh");//替换找到的sixth

cout << str << '\n';

 可以看出被替换了

6.substr

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	string str = "We think in generalities, but we live in details.";
	

	string str2 = str.substr(3, 5);    //从pos=3的位置截取5个字符 

	size_t pos = str.find("live");     

	string str3 = str.substr(pos);   //从pos位置截取pos后面所有字符  

	cout << str2 << ' ' << str3 << '\n';

	return 0;
}


 

 

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

5.string非成员函数

 

 总结

以上就是string的介绍和使用,和C语言比起来,string的使用非常的爽,刷题爽,写程序爽!!!

  • 26
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
以下是一个简单的C++文字RPG游戏的示例代码,其中包括了基本的角色、战斗和物品系统: ```c++ #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; // 角色 class Character { public: string name; int hp; int atk; int def; int gold; Character(string n, int h, int a, int d, int g) { name = n; hp = h; atk = a; def = d; gold = g; } // 攻击函数 void attack(Character& other) { int damage = atk - other.def; if (damage < 0) { damage = 0; } other.hp -= damage; cout << name << "攻击了" << other.name << ",造成了" << damage << "点伤害。" << endl; } // 是否死亡 bool isDead() { return hp <= 0; } }; // 物品 class Item { public: string name; int price; int hp; int atk; int def; Item(string n, int p, int h, int a, int d) { name = n; price = p; hp = h; atk = a; def = d; } }; // 商店 class Shop { public: Item items[3]; Shop() { items[0] = Item("草药", 10, 20, 0, 0); items[1] = Item("铁剑", 50, 0, 10, 0); items[2] = Item("铁甲", 100, 0, 0, 10); } // 显示商店物品 void showItems() { cout << "欢迎光临!以下是本店的物品:" << endl; for (int i = 0; i < 3; i++) { cout << i + 1 << ". " << items[i].name << " - " << items[i].price << "金币" << endl; } } // 购买物品 bool buy(Character& c, int choice) { if (c.gold < items[choice - 1].price) { cout << "金币不足,法购买!" << endl; return false; } c.gold -= items[choice - 1].price; c.hp += items[choice - 1].hp; c.atk += items[choice - 1].atk; c.def += items[choice - 1].def; cout << "购买成功!" << endl; return true; } }; // 战斗函数 void battle(Character& player, Character& enemy) { cout << "你遇到了一只" << enemy.name << ",准备战斗!" << endl; while (!player.isDead() && !enemy.isDead()) { player.attack(enemy); if (enemy.isDead()) { cout << enemy.name << "被你打败了!" << endl; player.gold += enemy.gold; return; } enemy.attack(player); if (player.isDead()) { cout << "你被" << enemy.name << "打败了!" << endl; return; } } } int main() { srand(time(NULL)); // 初始化随机数种子 // 初始化角色和商店 Character player("勇者", 100, 10, 5, 50); Character enemies[3] = { Character("史莱姆", 30, 5, 2, 10), Character("骷髅兵", 50, 10, 5, 20), Character("巨龙", 100, 20, 10, 50) }; Shop shop; // 游戏循环 while (true) { cout << "你的状态 - HP:" << player.hp << " ATK:" << player.atk << " DEF:" << player.def << " 金币:" << player.gold << endl; cout << "请选择操作:" << endl; cout << "1. 进入商店" << endl; cout << "2. 进行战斗" << endl; cout << "3. 离开游戏" << endl; int choice; cin >> choice; switch (choice) { case 1: shop.showItems(); cout << "请选择要购买的物品(输入编号):" << endl; cin >> choice; shop.buy(player, choice); break; case 2: battle(player, enemies[rand() % 3]); break; case 3: cout << "游戏结束,欢迎再次光临!" << endl; return 0; default: cout << "无效的操作!" << endl; break; } } return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值