【C++】list 与 string 基础与实现字符串操作

【C++】使用 list 与 string 实现基础字符串操作

文章目录

    • 一、字符串的基础操作
      • 1.1 - startsWith
      • 1.2 - endsWith
      • 1.3 - trim
      • 1.4 - indexOf
      • 1.5 - replaceAll
    • 二、list 基础操作
      • 2.1 - 遍历
        • 2.1.1 - 使用迭代器访问
        • 2.1.2 - 使用基于范围的 for 循环遍历
        • 2.1.3 - 使用标准算法库遍历
      • 2.2 - 访问元素
      • 2.3 - 删除元素
    • 三、list\<string\>
      • 3.1 - 移除所有空字符串元素
      • 3.2 - 遍历字符串并应用 trim
      • 3.3 - 移除连续的空白行

一、字符串的基础操作

1.1 - startsWith

bool startsWith(const std::string& fullString, const std::string& starting)
{if (fullString.length() >= starting.length()) {return (0 == fullString.compare(0, starting.length(), starting));} else {return false;}
}

1.2 - endsWith

bool endsWith(const std::string& fullString, const std::string& ending) {if (fullString.length() >= ending.length()){return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));}else{return false;}
}

1.3 - trim

用于移除字符串前后两端的空白符

// Function to trim whitespace from the beginning and end of a string
std::string trim(const std::string& str) {size_t first = str.find_first_not_of(" \t\n\r\f\v");// No non-whitespace charactersif (first == std::string::npos){    // 如果从头开始非空白符找不到,说明所有的字符都是空白符,因此全部去掉return "";  }size_t last = str.find_last_not_of(" \t\n\r\f\v");// 即便 last 为 string::npos substr 也会做处理。return str.substr(first, (last - first + 1));
}

或者

#include <algorithm>
#include <cctype>// 去除字符串左侧空白
static inline void ltrim(std::string &s) {s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {return !std::isspace(ch);}));
}// 去除字符串右侧空白
static inline void rtrim(std::string &s) {s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {return !std::isspace(ch);}).base(), s.end());
}// 去除字符串两侧空白
static inline void trim(std::string &s) {ltrim(s);rtrim(s);
}

1.4 - indexOf

用于获取第一个子串的位置索引,如果找不到则返回 -1。

// Function to find the index of the first occurrence of a substring
int indexOf(const std::string& str, const std::string& substr)
{size_t pos = str.find(substr);return (pos != std::string::npos) ? static_cast<int>(pos) : -1;
}

1.5 - replaceAll

// 替换字符串中所有匹配的子字符串
void replaceAll(std::string& source, const std::string& from, const std::string& to)
{// 如果字符串为空则返回。if (from.empty()) { return; }size_t startPos = 0;while ((startPos = source.find(from, startPos)) != std::string::npos) {source.replace(startPos, from.length(), to);startPos += to.length(); // 在替换后移动过去新增的部分}
}

二、list 基础操作

2.1 - 遍历

2.1.1 - 使用迭代器访问
#include <iostream>
#include <list>
std::list<int> myList = {1, 2, 3, 4, 5};// 使用迭代器遍历 std::list
for (auto it = myList.begin(); it != myList.end(); ++it)
{std::cout << *it << " ";
}
std::cout << std::endl;
2.1.2 - 使用基于范围的 for 循环遍历
#include <iostream>
#include <list>
// 使用范围基 for 循环遍历 std::list
for (int elem : myList) 
{std::cout << elem << " ";
}
std::cout << std::endl;
2.1.3 - 使用标准算法库遍历
#include <iostream>
#include <list>
#include <algorithm> // for std::for_each
std::list<int> myList = {1, 2, 3, 4, 5};// 使用 std::for_each 遍历 std::list
std::for_each(myList.begin(), myList.end(), [](int elem) {std::cout << elem << " ";
});
std::cout << std::endl;

2.2 - 访问元素

访问第 N 个元素

#include <iostream>
#include <list>std::list<int> myList = {10, 20, 30, 40, 50};
int N = 3;  // 以 0 为起始索引,访问第 4 个元素
auto it = myList.begin();
std::advance(it, N);  // 使用 std::advance 前进到第 N 个元素if (it != myList.end()) {std::cout << "The element at index " << N << " is " << *it << std::endl;
} else {std::cout << "Index out of range." << std::endl;
}

2.3 - 删除元素

删除前 N 个元素

std::list<int> myList = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int N = 3;  // 指定要删除的元素数量
if (N <= myList.size()) {// 获取开始到第 N 个元素的迭代器auto it = myList.begin();std::advance(it, N);  // 移动迭代器到第 N 个位置// 从开始到第 N 个元素进行删除myList.erase(myList.begin(), it);
}// 打印剩余的元素
for (int elem : myList) {std::cout << elem << " ";
}
std::cout << std::endl;

三、list<string>

3.1 - 移除所有空字符串元素

#include <iostream>
#include <list>
#include <string>// 创建并初始化一个 std::list<std::string>
std::list<std::string> strings = {"Hello", "", "World", "", "C++17", ""};
// 输出原始列表
std::cout << "Original list:" << std::endl;
for (const auto& str : strings)
{std::cout << "'" << str << "'" << std::endl;
}
// 移除所有空字符串
strings.remove_if([](const std::string& s) { return s.empty(); });
// 输出修改后的列表
std::cout << "\nList after removing empty strings:" << std::endl;
for (const auto& str : strings) {std::cout << "'" << str << "'" << std::endl;
}

3.2 - 遍历字符串并应用 trim

std::list<std::string> myStrings = {"  hello  ", "  world!  ", "  example  "};// 遍历列表并应用 trim 函数
for (std::string& str : myStrings) {trim(str);
}
// 打印修剪后的字符串列表
for (const auto& str : myStrings) {std::cout << '"' << str << '"' << std::endl;
}

3.3 - 移除连续的空白行

将多个连续的空白行替换为一个空白行

#include <iostream>
#include <list>
#include <string>
#include <iterator>void compressEmptyLines(std::list<std::string>& lines) {bool lastWasEmpty = false;for (auto it = lines.begin(); it != lines.end(); ) {// 检查当前行是否为空白(或只包含空格)bool isEmpty = it->find_first_not_of(" \t\n\v\f\r") == std::string::npos;if (isEmpty) {if (lastWasEmpty) {// 如果当前行是空的,并且上一行也是空的,删除当前行it = lines.erase(it);} else {// 如果当前行是空的,但上一行不是,保留这行并标记lastWasEmpty = true;++it;}} else {// 如果当前行不是空的,继续前进lastWasEmpty = false;++it;}}
}int main() {std::list<std::string> lines = {"Hello"," "," ","World","","","!"," ","End"};compressEmptyLines(lines);// 输出处理后的列表for (const auto& line : lines) {std::cout << '"' << line << '"' << std::endl;}return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/886520.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CI/CD认识

CI/CD 是 Continuous Integration&#xff08;持续集成&#xff09; 和 Continuous Delivery/Deployment&#xff08;持续交付/部署&#xff09; 的缩写&#xff0c;是一种软件开发和运维实践&#xff0c;旨在通过自动化和持续迭代来提高开发效率、代码质量以及交付速度。 CI&…

Git主干分支master开发优缺点

优缺点 主干开发&#xff1a;是指开发人员直接向主干&#xff08;习惯上主干分支通常为&#xff1a;main或master&#xff09;提交/推送代码。通常开发团队的成员1天至少一次地将代码提交到主干分支&#xff0c;在到达发布条件时&#xff0c;从主干拉出发布分支通常为&#xf…

药典新篇:Spring Boot助力中药实验管理

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理中药实验管理系统的相关信息成为必然。开发…

使用 Python 和 Py2Neo 构建 Neo4j 管理脚本

Neo4j 是一个强大的图数据库&#xff0c;适合处理复杂的关系型数据。借助 Python 的 py2neo 库&#xff0c;我们可以快速实现对 Neo4j 数据库的管理和操作。本文介绍一个功能丰富的 Python 脚本&#xff0c;帮助用户轻松管理 Neo4j 数据库&#xff0c;包含启动/停止服务、清空数…

举例通俗易懂地理解数据结构

以下是几个数据结构的基础讲解&#xff1a; 1. 数组 (Array) 数组是最简单、最常用的数据结构。它在内存中分配一块连续的空间&#xff0c;并且所有元素的类型相同。 C语言示例&#xff1a; #include <stdio.h>int main() {int arr[5] {10, 20, 30, 40, 50};// 访问数…

Apache Doris:深度优化与最佳实践

引言 在前两篇文章中&#xff0c;我们已经介绍了 Apache Doris 的基本概念、安装配置、基础操作以及一些高级特性。本文将进一步深入探讨 Doris 的性能优化技巧、高级查询优化、数据建模最佳实践以及常见问题的解决方法。通过本文&#xff0c;读者将能够更好地理解和应用 Dori…

MATLAB 使用教程 —— 命令窗口输入命令,工作区显示变量

命令在命令窗口输入变量在工作区显示 MATLAB 桌面包含的面板如下&#xff1a; 当前文件夹 - 此面板允许访问项目文件夹和文件。命令窗口 - 这是主要区域&#xff0c;用户在命令行中输入命令&#xff0c;命令提示符(>>).工作区 - 工作区显示所有变量&#xff0c;无论是创…

nodejs入门(1):nodejs的前后端分离

一、引言 我关注nodejs还是从前几年做了的一个电力大数据展示系统开始的&#xff0c;当然&#xff0c;我肯定是很多年的计算机基础的&#xff0c;万变不离其宗。 现在web网站都流行所谓的前后端结构&#xff0c;不知不觉我也开始受到这个影响&#xff0c;以前都是前端直接操作…

前端开发之打印功的使用和实例(vue-print-nb)

通过插件来进行实现 前言效果图1、安装插件vue2vue32、 引入Vue项目2、 使用2.1、在项目中创建按钮并且使用v-print绑定绑定打印事件2.2、编写要打印的内容,给内容附加唯一的id2.3、绑定的时间的方法和参数3、整体代码(此代码是通过vue3来进行实现的但是逻辑都是一样的)前言…

一文简单了解Android中的input流程

在 Android 中&#xff0c;输入事件&#xff08;例如触摸、按键&#xff09;从硬件传递到应用程序并最终由应用层消费。整个过程涉及多个系统层次&#xff0c;包括硬件层、Linux 内核、Native 层、Framework 层和应用层。我们将深入解析这一流程&#xff0c;并结合代码逐步了解…

opencv kdtree pcl kdtree 效率对比

由于项目中以一个环节需要使用kdtree ,对性能要求比较严苛&#xff0c;所以看看那个kdtree效率高一些。对比了opencv和pcl。 #include <array> #include <deque> #include <fstream> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp…

python贪心算法实现(纸币找零举例)

目录 问题描述 贪心策略 Python代码实现 代码解释 示例输出 注意事项 问题描述 给定一组纸币面值和一个目标金额&#xff0c;找出用最少数量的纸币来找零的方法。 贪心策略 每次选择面值最大的纸币&#xff0c;直到无法继续选择为止。 Python代码实现 def min_bills…

学习日志011--模块,迭代器与生成器,正则表达式

一、python模块 在之前学习c语言时&#xff0c;我们学了分文件编辑&#xff0c;那么在python中是否存在类似的编写方式&#xff1f;答案是肯定的。python中同样可以实现分文件编辑。甚至还有更多的好处&#xff1a; ‌提高代码的可维护性‌&#xff1a;当代码被分成多个文件时…

idea 弹窗 delete remote branch origin/develop-deploy

想删除远程分支&#xff0c;就选delete&#xff0c;仅想删除本地分支&#xff0c;选cancel&#xff1b; 在 IntelliJ IDEA 中遇到弹窗提示删除远程分支 origin/develop-deploy&#xff0c;这通常是在 Git 操作过程中出现的情况&#xff0c;可能是在执行如 git branch -d 或其他…

湘潭大学软件工程算法设计与分析考试复习笔记(一)

文章目录 前言随机类&#xff08;第七章&#xff09;随机概述数值随机化舍伍德拉斯维加斯蒙特卡罗 模拟退火遗传人工神经网络 回溯&#xff08;第五章&#xff09;动态规划&#xff08;第四章&#xff09;后记 前言 考试还剩十一天&#xff0c;现在准备开始复习这门课了。好像全…

Python常用魔术方法 (学习笔记)

文章目录 一、魔术方法是什么&#xff1f;二、使用步骤1.__ str __(self):2.__ lt__(self):3. __ le __(self):4. __ eq __(self): 总结 一、魔术方法是什么&#xff1f; 在Python中&#xff0c;魔术方法&#xff08;也称为特殊方法或双下划线方法&#xff09;是一类具有特殊用…

手写模拟Spring Boot自动配置功能

引言 随着微服务架构的兴起&#xff0c;Spring Boot作为一种快速开发框架&#xff0c;因其简化了Spring应用的初始搭建和开发过程&#xff0c;受到了广大开发者的青睐。自动配置作为Spring Boot的核心特性之一&#xff0c;大大减少了手动配置的工作量&#xff0c;提高了开发效…

Linux性能优化之火焰图的起源

Linux火焰图的起源与性能优化专家 Brendan Gregg 密切相关&#xff0c;他在 2011 年首次提出这一工具&#xff0c;用于解决性能分析过程中可视化和数据解读的难题。 1. 背景&#xff1a;性能优化的需求 在现代计算中&#xff0c;性能优化往往需要对程序执行中的热点和瓶颈进行…

【论文精读】GOT-OCR2.0源码论文——打破传统OCR流程的多模态视觉-语言大模型架构:预训练VitDet 视觉模型+ 阿里通义千问Qwen语言模型

作为本系列的开篇文章&#xff0c;首先定下本系列的整体基调。论文精读系列&#xff0c;旨在记录研读深度学习、强化学习相关论文的个人心得和理解&#xff0c;仅供参考&#xff0c;欢迎指正错误和研究探讨。 所有文章只会摘选论文部分进行分析&#xff0c;且不一定按原文行文顺…

动态规划之股票系列

123. 买卖股票的最佳时机 III 188. 买卖股票的最佳时机 IV 309. 买卖股票的最佳时机含冷冻期 1.AC代码: class Solution {public int maxProfit(int[] prices) {int nprices.length;int[][] dpnew int[n][5];dp[0][1]-prices[0];dp[0][3]-prices[0];for(int i1;i<n;i){/…