当前位置: 首页 > news >正文

C++ 中常见的字符串定义方式及其用法

引言
最近在学习C++,下面将从基础到进阶的顺序,列出一些 C++ 中常见的字符串定义方式及其用法,包含完整代码和详细注释,加深对代码的理解。

C 风格字符串(char*或 char[])

  • 定义方式
#include <iostream>int main() {// 字符串字面量(不可修改)const char* str1 = "Hello";// 字符数组(可修改)char str2[] = "World";// 手动初始化字符数组(需留空间给 '\0')char str3[6] = {'H', 'e', 'l', 'l', 'o', '\0'};std::cout << str1 << " " << str2 << " " << str3 << std::endl;return 0;
}// 输出结果:Hello World Hello
  • 特点

    结尾必须是 ‘\0’

    不安全,容易越界或引发未定义行为

    推荐尽量用 std::string 替代

C++ 标准字符串(std::string)

  • 常见定义方式与用法
#include <iostream>
#include <string>int main() {// 定义字符串std::string s1 = "Hello";std::string s2("World");std::string s3 = s1 + ", " + s2 + "!";  // 字符串拼接std::cout << s3 << std::endl;  // 输出:Hello, World!// 字符访问std::cout << "第一个字符:" << s3[0] << std::endl;std::cout << "最后一个字符:" << s3.back() << std::endl;// 长度与清空std::cout << "长度:" << s3.length() << std::endl;s3.clear();std::cout << "是否为空:" << s3.empty() << std::endl;return 0;
}/*
输出结果:
Hello, World!
第一个字符:H
最后一个字符:!
长度:13
是否为空:1
*/

字符串数组或向量

  • 使用 std::vectorstd::string
#include <iostream>
#include <vector>
#include <string>int main() {std::vector<std::string> fruits = {"apple", "banana", "cherry"};// 添加元素fruits.push_back("date");// 遍历for (const std::string& fruit : fruits) {std::cout << fruit << std::endl;}return 0;
}/*
输出结果:
apple
banana
cherry
date
*/
  • 使用 std::array<std::string, N>(定长数组)
#include <iostream>
#include <array>
#include <string>int main() {std::array<std::string, 3> days = {"Monday", "Tuesday", "Wednesday"};for (const auto& day : days) {std::cout << day << std::endl;}  // 使用 auto 自动识别数据类型return 0;
}/*
输出结果:
Monday
Tuesday
Wednesday
*/

字符串处理常用操作

  • 查找和替换
#include <iostream>
#include <string>int main() {std::string text = "I like apples and apples are sweet.";// 查找第一个"apple"size_t pos = text.find("apples");if (pos != std::string::npos) {std::cout << "找到位置:" << pos << std::endl;}// 替换第一个"apples"为"oranges"text.replace(pos, 6, "oranges");std::cout << "替换后:" << text << std::endl;return 0;
}
  • 子串、大小写、比较
#include <iostream>
#include <string>int main() {std::string s = "HelloWorld";// 提取子串std::string sub = s.substr(0, 5);  // "Hello"// 比较if (s == "HelloWorld") {std::cout << "字符串相等" << std::endl;}// 大小写转换(手动方式)for (char& c : s) {c = tolower(c);  // 或者 toupper(c)}std::cout << s << std::endl;return 0;
}

其他容器中的字符串用法

  • std::dequestd::string
#include <iostream>
#include <deque>
#include <string>int main() {std::deque<std::string> queue;queue.push_back("first");queue.push_back("second");queue.push_front("zero");for (const auto& item : queue) {std::cout << item << std::endl;}return 0;
}
  • std::map<std::string, std::string>
#include <iostream>
#include <map>
#include <string>int main() {std::map<std::string, std::string> dict;dict["apple"] = "苹果";dict["banana"] = "香蕉";for (const auto& [eng, chi] : dict) {std::cout << eng << ": " << chi << std::endl;}return 0;
}

字符串与数值转换

#include <iostream>
#include <string>int main() {std::string numStr = "123";int num = std::stoi(numStr);  // string -> intdouble d = std::stod("3.1415");  // string -> doublestd::string s = std::to_string(42);  // int -> stringstd::cout << "整数:" << num << ",浮点数:" << d << ",字符串:" << s << std::endl;return 0;
}
http://www.xdnf.cn/news/1123129.html

相关文章:

  • 使用Java完成下面项目
  • 解决chrome v2 版本插件不支持
  • uni-app在安卓设备上获取 (WIFI 【和】以太网) ip 和 MAC
  • C语言-数据输入与输出
  • java学习 day4 分布式锁
  • 【Learning Notes】 Derak Callan‘s Business English P38~40
  • 【【异世界历险之数据结构世界(二叉树)】】
  • Why C# and .NET are still relevant in 2025
  • 安装Keycloak并启动服务(macOS)
  • 4.2TCP/IP
  • USB读写自动化压力测试
  • 小波变换 | 离散小波变换
  • AI驱动的软件工程(下):AI辅助的质检与交付
  • FreeRTOS之链表操作相关接口
  • 人工智能如何重构能源系统以应对气候变化?
  • 29.安卓逆向2-frida hook技术-逆向os文件(二)IDA工具下载和使用
  • kali安装失败-选择并安装软件包-一步到位
  • 7.15 窗口函数 | 二分 | 位运算 | 字符串dp
  • C# TCP粘包与拆包深度了解
  • MCP基础知识二(实战通信方式之Streamable HTTP)
  • 微信131~140
  • 属性绑定
  • 零基础 “入坑” Java--- 十一、多态
  • IDEA中使用Servlet,tomcat输出中文乱码
  • 《星盘接口2:NVMe风暴》
  • [spring6: Resource ResourceLoader ResourceEditor]-加载资源
  • 【Java笔记】七大排序
  • 现有医疗AI记忆、规划与工具使用的创新路径分析
  • 融合竞争学习与高斯扰动的多目标加权平均算法(MOWAA)求解多无人机协同路径规划(多起点多终点,起始点、无人机数、障碍物可自定义),提供完整MATLAB代码
  • 嵌入式硬件篇---晶体管的分类