C++ ——string类

一、什么是string类,为什么要使用string类

    什么是 string 类?

string 类是 C++ 标准库中的一个类,用于表示字符串。它封装了一系列操作字符串的方法,例如创建、修改、比较、连接、搜索等。string 类提供了更高级别、更易用的接口,使得处理字符串变得更加简单和高效。

    为什么要学习 string 类?

  1. 安全性:使用 string 类可以避免许多与字符数组相关的安全性问题,比如缓冲区溢出。
  2. 便利性string 类提供了丰富的成员函数,使得对字符串的操作更加便捷,不需要手动管理内存。
  3. 高效性string 类实现了许多字符串操作的优化算法,性能通常比手动操作字符数组更高。
  4. 可移植性string 类是 C++ 标准库的一部分,因此可以在不同的平台和编译器上使用,确保代码的可移植性。
  5. 标准化string 类是 C++ 标准库的一部分,学习并熟练掌握它可以提高代码的标准化程度,使得代码更易于理解和维护。

总之,学习 string 类是 C++ 程序员必备的技能之一。它是处理字符串的标准方式,能够提高代码的安全性、可读性和可维护性。

二、string类的相关用法

  1.string的定义方式

#include <iostream>
#include <string>

int main() {
    // 1. 使用默认构造函数定义空字符串
    std::string str1;

    // 2. 使用字符串字面量初始化字符串
    std::string str2 = "Hello";

    // 3. 使用拷贝构造函数初始化字符串
    std::string str3(str2);

    // 4. 使用赋值运算符赋值给字符串
    std::string str4 = str3;

    // 5. 使用重复字符初始化字符串
    std::string str5(5, 'A');

    // 6. 使用子字符串初始化字符串
    std::string str6("abcdef", 3, 2); // 从 "abcdef" 的第三个字符开始,取两个字符

    // 打印所有字符串
    std::cout << "str1: " << str1 << std::endl;
    std::cout << "str2: " << str2 << std::endl;
    std::cout << "str3: " << str3 << std::endl;
    std::cout << "str4: " << str4 << std::endl;
    std::cout << "str5: " << str5 << std::endl;
    std::cout << "str6: " << str6 << std::endl;

    return 0;
}
  • 使用不同的方式定义了多个字符串对象。
  • 打印每个字符串对象的值。

运行结果:

str1: 
str2: Hello
str3: Hello
str4: Hello
str5: AAAAA
str6: cd

 2.string的插入

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";

    // 在指定位置插入字符
    str.insert(5, ", world");

    std::cout << "After insert: " << str << std::endl;

    return 0;
}
  • 使用 insert() 函数在指定位置插入字符。
  • 在位置 5(即字符 'o' 后面)插入字符串 ", world"。

运行结果:

After insert: Hello, world

 3.string的拼接

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = " world";

    // 使用 '+' 运算符拼接字符串
    std::string combined = str1 + str2;

    std::cout << "After concatenation: " << combined << std::endl;

    return 0;
}

使用 '+' 运算符拼接两个字符串。

After concatenation: Hello world

 4.string的删除

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 删除从位置 5 开始的 7 个字符
    str.erase(5, 7);

    std::cout << "After erase: " << str << std::endl;

    return 0;
}

使用 erase() 函数删除字符串中的一部分字符。

After erase: Hello

5.string的查找

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 查找子字符串 ", wo"
    size_t pos = str.find(", wo");

    std::cout << "Position of ', wo': " << pos << std::endl;

    return 0;
}

 使用 find() 函数查找子字符串在原字符串中的位置。

Position of ', wo': 5

6.string的比较 

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "hello";

    // 比较两个字符串
    int result = str1.compare(str2);

    if (result == 0) {
        std::cout << "Strings are equal" << std::endl;
    } else if (result < 0) {
        std::cout << "String 1 is less than String 2" << std::endl;
    } else {
        std::cout << "String 1 is greater than String 2" << std::endl;
    }

    return 0;
}

使用 compare() 函数比较两个字符串的大小。

String 1 is greater than String 2

 7.string的替换

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 替换子字符串 ", world" 为 "!"

    str.replace(5, 6, "!");

    std::cout << "After replace: " << str << std::endl;

    return 0;
}

使用 replace() 函数替换字符串中的一部分内容。

After replace: Hello!

8.string的交换

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";

    // 交换两个字符串
    str1.swap(str2);

    std::cout << "str1: " << str1 << std::endl;
    std::cout << "str2: " << str2 << std::endl;

    return 0;
}

使用 swap() 函数交换两个字符串的内容。 

str1: World
str2: Hello

9. string的大小和容量

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 获取字符串的大小和容量
    std::cout << "Size of the string: " << str.size() << std::endl;
    std::cout << "Capacity of the string: " << str.capacity() << std::endl;

    return 0;
}

 使用 size() 函数获取字符串的大小(即字符数)。

使用 capacity() 函数获取字符串的容量(即可容纳的字符数)。

Size of the string: 12
Capacity of the string: 12

10.string中元素的访问 

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 访问字符串中的单个字符
    char ch = str[7];

    std::cout << "Character at position 7: " << ch << std::endl;

    return 0;
}

使用下标访问运算符 [] 访问字符串中的单个字符。

Character at position 7: w

11.string中运算符的使用

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = " world";

    // 使用 '+' 运算符拼接字符串
    std::string combined = str1 + str2;

    std::cout << "After concatenation: " << combined << std::endl;

    return 0;
}
使用 + 运算符拼接两个字符串。
After concatenation: Hello world

12.string中与迭代器相关的函数

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";

    // 使用正向迭代器遍历字符串并打印每个字符
    std::cout << "Forward iteration: ";
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

 str.begin() 返回指向字符串起始位置的迭代器。str.end() 返回指向字符串末尾位置的迭代器。使用 std::string::iterator 定义迭代器类型。使用迭代器遍历字符串,并打印每个字符。

Forward iteration: H e l l o ,   w o r l d ! 
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";

    // 使用反向迭代器遍历字符串并打印每个字符
    std::cout << "Reverse iteration: ";
    for (std::string::reverse_iterator rit = str.rbegin(); rit != str.rend(); ++rit) {
        std::cout << *rit << " ";
    }
    std::cout << std::endl;

    return 0;
}

str.rbegin() 返回指向字符串末尾的逆向迭代器。str.rend() 返回指向字符串起始位置的逆向迭代器。使用 std::string::reverse_iterator 定义逆向迭代器类型。使用逆向迭代器遍历字符串,并打印每个字符。

Reverse iteration: ! d l r o w   , o l l e H 

13.string与字符串之间的转换 

#include <iostream>
#include <string>

int main() {
    // 1. string 转换为 C 风格字符串
    std::string str1 = "Hello";
    const char* cstr = str1.c_str();

    std::cout << "C-style string: " << cstr << std::endl;

    // 2. C 风格字符串转换为 string
    const char* cstr2 = " world";
    std::string str2 = cstr2;

    std::cout << "String from C-style string: " << str2 << std::endl;

    return 0;
}

 将 string 对象转换为 C 风格字符串,使用 c_str() 函数。将 C 风格字符串转换为 string 对象,直接赋值即可。

C-style string: Hello
String from C-style string:  world

14.string中子字符串的提取 

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world";

    // 提取子字符串
    std::string sub = str.substr(7, 5); // 从位置 7 开始,提取 5 个字符

    std::cout << "Subtring: " << sub << std::endl;

    return 0;
}

使用 substr() 函数从原始字符串中提取子字符串。

Subtring: world

15.string中的getline函数 

#include <iostream>
#include <string>

int main() {
    std::string str;

    // 从标准输入读取一行字符串
    std::cout << "Enter a line: ";
    std::getline(std::cin, str);

    std::cout << "You entered: " << str << std::endl;

    return 0;
}

使用 std::getline() 函数从标准输入流中读取一行字符串。

Enter a line: Hello, world
You entered: Hello, world

  • 19
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的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; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值