转自:https://cloud.tencent.com/developer/article/1143683

C++中的字符串类型

常用的C++的字符串类型主要是std::string。它是模板std::basic_string的一个实例化。另外还有三个实例化std::wstringstd::u16stringstd::u32string,不过不是很常用。

std::basic_string<T>
std::string            std::basic_string<char>
std::wstring           std::basic_string<wchar_t>
std::u16string         std::basic_string<char16_t>
std::u32string         std::basic_string<char32_t>

具体可以参考:http://en.cppreference.com/w/cpp/string/basic_string

std::string

标准库中,std::string的成员函数和相关的算法特别多,从上面给出的链接里的内容,粗略计算一下,包括所有的重载函数,也有百余个了。但是在实际的工作使用中,很多时候,总是会感觉,C++对字符串的处理支持实在是弱爆了……感觉这个具有百余个方法的“巨”类用起来总是捉襟见肘。

std::string中的很多操作都是基于迭代器的——这样的话,很多操作,我们都需要先调用find或者直接遍历字符串拿到操作区间的迭代器,然后再进行实际的操作。成员函数中:inserterasereplace都是基于迭代器的操作。

同时,std::string也没有提供一些常用的字符串处理的方法,比如:简单的大小写转换,字符串连接,字符串分割等。

C++11中,提供了std::string的数字和字符串相互转换的算法:

  • 字符串==>数字 stoi string to int stol string to long stoll string to long long stoul string to unsigned long stoull string to unsigned long long stof string to float stod string to double stold string to long double
  • 数字==>字符串 to_string to_wstring

Boost中的字符串处理

Boost库通过算法的形式,提供了一些处理C++字符串的函数,虽然比起Java或者其它一些动态语言还是略显不足,但也算在一定程度上方便了我们对C++的字符串处理。

除了普通的字符串处理算法,Boost库还提供了一个正则表达式的函数库Boost.Regex。Boost.Regex已经被纳入到C++11的标准之中,但是我们常用的g++4.8.x(比如ubuntu14.04默认的g++版本就是4.8.x,公司的g++版本也是4.8.x)的C++标准库还没有实现正则表达式。

实际上,g++4.8.x已经定义了标准库正则表达式的类型和接口,但是只是占了个坑,并没有真正实现……结果可以编译通过,但是运行一直抛出异常。gcc4.9才真正实现了标准库的正则表达式。

下面通过例子介绍一个Boost提供的字符串处理算法以及Boost.Regex的用法。

Boost的字符串算法

  • 头文件:#include <boost/algorithm/string.hpp>
  • Boost的很多修改字符串的算法都提供了直接修改传入字符串,名字不带copy返回一个新的字符串,名字带copy两个版本。

字符串大小写转换

C++标准库竟然连一个字符串大小写的转换函数都没有提供。

  • boost::algorithm::to_upper(), boost::algorithm::to_lower()直接修改传入的字符串,将其转换为对应字符串的大写或小写。
  • boost::algorithm::to_upper_copy(), boost::algorithm::to_lower_copy()返回一个新的大写或小写字符串。
  • 例子:
#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{std::string s("AbCdefG123 HijkLmn");cout << boost::algorithm::to_upper_copy(s) << endl;boost::algorithm::to_lower(s);cout << s << endl;
}
输出结果:
ABCDEFG123 HIJKLMN
abcdefg123 hijklmn

子串删除。

  • std::string提供了几个erase成员函数,都是基于“位置(下标或迭代器)”的删除:
basic_string& erase(size_type index = 0, size_type count = npos);
iterator erase(iterator position);
iterator erase(const_iterator position);
iterator erase(iterator first, iterator last);
iterator erase(const_iterator first, const_iterator last);
  • STL提供的remove系列的算法,由于其需要与其他容器通用,其删除时的比较函数只能是一个字符之间的比较(std::string中的一个字符相当于vector中的一个元素)。
ForwardIt remove(ForwardIt first, ForwardIt last, const T& value);
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p);
OutputIt remove_copy(InputIt first, InputIt last, OutputIt d_first, const T& value);
OutputIt remove_copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate p);
  • Boost提供了删除字符串子串的算法。
erase_all()删除主串中所有相等的子串。
erase_first()删除主串中第一个相等的子串。
erase_nth()删除主串中的第n个子串。**注意这里的n是从0开始的。**
erase_head()删除主串的前n个字符。
erase_tail()删除组成的后n个字符。
erase系列的copy版本

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{std::string s("AbCdefG123 HijkLmn");s += s;s += s;string s0 = s;cout << "Input String: " << s0 << endl;cout << boost::algorithm::erase_all_copy(s0, "AbC") << endl;cout << boost::algorithm::ierase_all_copy(s0, "ABC") << endl;cout << boost::algorithm::erase_first_copy(s0, "defG123") << endl;cout << boost::algorithm::ierase_first_copy(s0, "DEFG123") << endl;cout << boost::algorithm::erase_nth_copy(s0, "HijkLmn", 1) << endl;cout << boost::algorithm::ierase_nth_copy(s0, "HIJKLMN", 1) << endl;cout << boost::algorithm::erase_head_copy(s0, 3) << endl;cout << boost::algorithm::erase_tail_copy(s0, 5) << endl;
}
输出结果:
Input String: AbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmn
defG123 HijkLmndefG123 HijkLmndefG123 HijkLmndefG123 HijkLmn
defG123 HijkLmndefG123 HijkLmndefG123 HijkLmndefG123 HijkLmn
AbC HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmn
AbC HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmn
AbCdefG123 HijkLmnAbCdefG123 AbCdefG123 HijkLmnAbCdefG123 HijkLmn
AbCdefG123 HijkLmnAbCdefG123 AbCdefG123 HijkLmnAbCdefG123 HijkLmn
defG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmn
AbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 HijkLmnAbCdefG123 Hi

子串查找

  • Boost的这些字符串的find算法的返回值都是boost::iterator_range类型的一对迭代器。
  • find_first() 查找第一个匹配的子串。std::string::find能实现一样的功能。(find_first的实现应该是封装了这个成员函数,不过个人感觉这个算法用起来更方便。)
  • find_last() 查找最后一个匹配的子串。std::string::rfind能实现一样的功能。
  • find_nth() 查找第n(n>=0)个匹配的字符串。
  • find_head(s, n) 返回字符串的前n个字符。
  • find_tail(s, n) 返回字符串的最后n个字符。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{std::string s("AbCdefG123 HijkLmn");s += s;s += s;cout << "Input String: " << s << endl;boost::iterator_range<std::string::iterator> itRange = boost::algorithm::find_first(s, "123");cout << itRange << endl;cout << itRange.begin() - s.begin() << endl;cout << itRange.end() - s.begin() << endl;itRange = boost::algorithm::find_last(s, "123");cout << itRange << endl;cout << itRange.begin() - s.begin() << endl;cout << itRange.end() - s.begin() << endl;itRange = boost::algorithm::find_nth(s, "123", 1);cout << itRange << endl;cout << itRange.begin() - s.begin() << endl;cout << itRange.end() - s.begin() << endl;itRange = boost::algorithm::find_head(s, 5);cout << itRange << endl;cout << itRange.begin() - s.begin() << endl;cout << itRange.end() - s.begin() << endl;itRange = boost::algorithm::find_tail(s, 5);cout << itRange << endl;cout << itRange.begin() - s.begin() << endl;cout << itRange.end() - s.begin() << endl;
}输出结果:
123
7
10
123
61
64
123
25
28
AbCde
0
5
jkLmn
67
72

连接字符串

  • Boost库提供了join()算法接受一个字符串容器作为第一个参数,根据第二个参数将这些字符串连接起来。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{vector<string> sVec{"ABC", "def", "GHIJK", "123456"};cout << boost::algorithm::join(sVec, "+**+") << endl;
}
输出结果:
ABC+**+def+**+GHIJK+**+123456

替换字符串

  • std::string提供的replace成员函数的重载很多,但是都只提供了基于位置(index或iterator)的替换操作 (http://en.cppreference.com/w/cpp/string/basic_string/replace), 没有基于子串比较再替换的操作。
  • Boost提供了基于比较的子串替换算法。
replace_first()替换第一个匹配的字符串。
replace_nth()替换第n(n>=0)个匹配的字符串。
replace_last()替换最后一个匹配的字符串。
replace_all()替换所有匹配的字符串。
replace系列的copy版本。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{string s("AbcDeFGHIJklmn");s += s;s += s;cout << "Input String: " << s << endl;cout << boost::algorithm::replace_all_copy(s, "AbcD", "**") << endl;cout << boost::algorithm::replace_first_copy(s, "AbcD", "**") << endl;cout << boost::algorithm::replace_last_copy(s, "AbcD", "**") << endl;cout << boost::algorithm::replace_nth_copy(s, "AbcD", 1, "**") << endl;
}
输出结果:
Input String: AbcDeFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmn
**eFGHIJklmn**eFGHIJklmn**eFGHIJklmn**eFGHIJklmn
**eFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmn
AbcDeFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmn**eFGHIJklmn
AbcDeFGHIJklmn**eFGHIJklmnAbcDeFGHIJklmnAbcDeFGHIJklmn

消除字符串两端的特殊字符

  • 很多时候,我们会希望删除字符左右两边的空白字符。Boost提供了几个算法来实现这个功能。
trim_left()删除字符串左边的空白。
trim_right()删除字符串右边的空白。
trim()删除字符串左右两边的空白。
trim系列的copy版本。
  • 有时候,我们想要删除的不仅仅是字符串左右两边的空白,而是其它一下特定的字符。
trim_left_if()
trim_right_if()
trim_if()
trim_if系列的copy版本,如果`trim_left_copy_if`...
  • Boost库的if系列算法通常传入一个"谓词参数", 如:
is_any_of
is_space 是否是空白字符。
is_alnum是否是字母或数字。
is_alpha是否时字母。
is_cntrl是否控制字符。
is_digit是否十进制数字。
is_graph是否图形字符。
is_lower是否小写字母。
is_print是否可打印字符。
is_punct是否标点符号。
is_upper是否大写字符。
is_xdigit是否十六进制数字。
is_from_range(from, to)是否from <= ch <= to。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{string s("   AbcDeF GHIJklmn      ");cout << "Input String: <" << s << '>' << endl;cout << '<' << boost::algorithm::trim_left_copy(s) << '>' << endl;cout << '<' << boost::algorithm::trim_right_copy(s) << '>' << endl;cout << '<' << boost::algorithm::trim_copy(s) << '>' << endl;cout << endl;string s1("==ABCD Efgh=IJK==-==   ");cout << "Input String: <" << s1 << '>' << endl;cout << '<' << boost::algorithm::trim_copy_if(s, boost::algorithm::is_any_of(" -=")) << '>' << endl;
}输出结果:Input String: <   AbcDeF GHIJklmn      ><AbcDeF GHIJklmn      ><   AbcDeF GHIJklmn><AbcDeF GHIJklmn>Input String: <==ABCD Efgh=IJK==-==   ><AbcDeF GHIJklmn>

匹配比较

starts_with(s, sub) s是否以sub开头, 即前缀。
ends_with(s, sub) s是否以sub结尾, 即后缀。
contains(s, sub) s是否包含sub。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
using namespace std;
int main()
{string s("abcdefGHIJKLMN");cout << boost::algorithm::starts_with(s, "abcd") << endl;cout << boost::algorithm::starts_with(s, "abcD") << endl;cout << boost::algorithm::ends_with(s, "MN") << endl;cout << boost::algorithm::ends_with(s, "mn") << endl;cout << boost::algorithm::contains(s, "efG") << endl;cout << boost::algorithm::contains(s, "WWW") << endl;
}
输出结果:
1
0
1
0
1
0

分割字符串

  • Boost库提供了split算法,根据指定的字符集合对字符串进行分割。

例子:

#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{string s("abc 123 cde");vector<string> sVec;boost::algorithm::split(sVec, s, boost::algorithm::is_space());for (auto& str : sVec){cout << str << endl;}cout << "--------分割线--------" << endl;s = " abc 123 cde   ";boost::algorithm::split(sVec, s, boost::algorithm::is_space());for (auto& str : sVec){cout << str << endl;}cout << "--------分割线--------" << endl;s = "--abc 123--cde-";boost::algorithm::split(sVec, s, boost::algorithm::is_any_of(" -"));for (auto& str : sVec){cout << str << endl;}
}
输出结果:
abc
123
cde
--------分割线--------
//空行
abc
123
cde
//空行
//空行
//空行
--------分割线--------
//空行
//空行
abc
123
//空行
cde
//空行
  • 注: boost的很多(但不是全部)字符串算法都带有忽略大小写的版本,相差只是以'i'开头。

正则表达式

简介

简单地说,Boost提供了三个类型三个算法来处理正则表达式:

  • 三个类型

    • 正则表达式使用boost::regex来表示。
    • 正则表达式的匹配的子串结果使用boost::smatchboost::sub_match来表示。
  • 三个算法
    • 判断整个字符串是否与正则表达式匹配:boost::regex_match()
    • 在字符串中搜索与正则表达式匹配的子串:boost::regex_search()
    • 替换掉字符串中所有与正则表达式匹配的字串:boost::regex_replace()

关于正则表达式的学习,可以参考这篇文章。

例子

** 下面通过例子和注释简单说明其用法。**

#include <boost/regex.hpp>
#include <iostream>
#include <string>
using namespace std;
int main()
{boost::regex rgx("(\\w+)\\s(\\w+)"); string s("abcd efgh");// boost::regex_match() 当字符串和正则表达式<完全匹配>的时候返回true,// 否则返回false。cout << boost::regex_match(s, rgx) << endl; cout << "========分割线========" << endl;// boost::regex_search() 找到第一个和正则表达式匹配的子串则返回true,// 具体匹配子串的信息存放在boost::smatch类型的参数里。否则返回false。// boost::smatch实际上是持有boost::sub_match的元素的容器。// boost::sub_match继承自类std::pair,// 对应的匹配子串由first和second成员表示:[first, second)。boost::smatch result;if (boost::regex_search(s, result, rgx)){for (size_t i = 0; i < result.size(); ++i){//result[0] 正则表达式的匹配结果。//result[1] 第一个分组的匹配结果。//result[2] 第二个分组的匹配结果。cout << result[i] << endl;}}cout << "========分割线========" << endl;rgx = "(\\w+)\\s\\w+";if (boost::regex_search(s, result, rgx)){for (size_t i = 0; i < result.size(); ++i){//result[0] 正则表达式的匹配结果//result[1] 分组的匹配结果cout << result[i] << endl;}}cout << "========分割线========" << endl;rgx = "\\w+\\s(\\w+)";if (boost::regex_search(s, result, rgx)){for (size_t i = 0; i < result.size(); ++i){cout << result[i] << endl;}}cout << "========分割线========" << endl;rgx = "\\w+\\s\\w+";if (boost::regex_search(s, result, rgx)){for (size_t i = 0; i < result.size(); ++i){cout << result[i] << endl;}}cout << "========分割线========" << endl;rgx = "(\\d+)\\s(\\w+)";if (boost::regex_search(s, result, rgx)){for (size_t i = 0; i < result.size(); ++i){cout << result[i] << endl;}}cout << "========分割线========" << endl;// 遍历正则匹配整个字符串。s = "abcd efgh ijk www";rgx = "\\w+\\s\\w+";auto begin = s.cbegin();auto end = s.cend();while (boost::regex_search(begin, end, result, rgx)){cout << result[0] << endl;begin = result[0].second;}cout << "========分割线========" << endl;// boost::regex_replace() 替换掉字符串中<所有>匹配的子串。//结果输出到一个Output Iterator。boost::regex_replace(std::ostreambuf_iterator<char>(std::cout), s.cbegin(), s.cend(), rgx, "666666");cout << endl;//直接返回结果cout << boost::regex_replace(s, rgx, "2233333") << endl; //每一个匹配
}输出结果:
1
========分割线========
abcd efgh
abcd
efgh
========分割线========
abcd efgh
abcd
========分割线========
abcd efgh
efgh
========分割线========
abcd efgh
========分割线========
========分割线========
abcd efgh
ijk www
========分割线========
666666 666666
2233333 2233333

C++字符串处理小结相关推荐

  1. php如果字符串有1 3 5,PHP常用字符串函数小结

    PHP常用字符串函数小结 来源:程序员人生   发布时间:2015-01-22 09:02:32 阅读次数:1594次 1.判断类型的函数 is_bool() //判断是不是为布尔型 is_float ...

  2. Java字符串使用小结

    摘要: 笔者近期在学习Java字符串这一部分的时候,Get到了一些比较新奇的点,准确的说,是和Python相比较而言的,因为笔者第一语言接触的是C和C++,而后便是Python,目前来说较为熟悉的就是 ...

  3. [OI]字符串DP小结

    顾名又思义,是在字符串上进行的DP操作.因为字符串本身可以看作是一个序列,所以有些时候字符串DP可以用区间DP来解决. P2246 SAC#1 - Hello World(升级版) 题目描述 在讲义的 ...

  4. Qt学习笔记之 字符串类型小结

    1. Qt常用字符串类型 1.1 QString QString是Unicode编码的字符串,存储一系列16位的QChar,每一个QChar对应一个Unicode 4.0编码的字符,详见<Qt学 ...

  5. PHP常用字符串函数小结

    最近面试被这个面到吐血,特地来fork一些. 来源:https://www.jb51.net/article/145084.htm 一.判断类型的函数 is_bool() //判断是否为布尔型 is_ ...

  6. java字符串匹配dp_[OI]字符串DP小结

    顾名又思义,是在字符串上进行的DP操作.因为字符串本身可以看作是一个序列,所以有些时候字符串DP可以用区间DP来解决. P2246 SAC#1 - Hello World(升级版) 题目描述 在讲义的 ...

  7. java常用字符串方法_Java常用字符串方法小结

    下面是对字符串操作的代码小总结.大部分是String类的 操作方法,需要的朋友可以参考下 public class StudyString { public static void main(Stri ...

  8. java 字符串用法_Java中的字符串用法小结

    本文实例总结了Java中的字符串用法.分享给大家供大家参考.具体分析如下: 字符串的本质是char类型的数组,但在java中,所有用双引号""声明的字符串都是一个String类的对 ...

  9. MFC中CString类字符串用法小结

    一. 赋值运算   二. 比较运算 注意:如果s1小于s2;则z等于-1:如果s1大于s2;则z等于1:如果s1等于s2;则z等于0: 三. 删除函数 四. 插入函数 五. 计算字符总个数函数 更加详 ...

最新文章

  1. mysql 账户管理_如何用MySQL 命令来实现账户管理
  2. 试验OSPF域内IP地址冲突会造成的安全问题
  3. 如何根据字典中值的大小,对字典中的项排序
  4. 小瓜牛漫谈 — String、StringBuffer、StringBuilder
  5. php 常用rpc框架,php的轻量级rpc框架yar
  6. oidc auth2.0_使用Spring Security 5.0和OIDC轻松构建身份验证
  7. 多模光纤收发器购买时需要注意什么问题?
  8. [程序员必备工具]分享一款不错的个人代码个人知识管理软件wiz
  9. QT 应用程序关闭某个窗口时,关闭打开的所有其他窗口并退出程序 【转】
  10. C#操作ini文件类
  11. ASP.NET学习顺序(转摘)
  12. python人脸识别训练模型_AI的强大!用Python实现一个简单的人脸识别--中享思途...
  13. 怎样快速提高计算机能力,如何提高算术能力?不借助计算机、笔、纸等工具,怎么能快速心算出多位数计算结果?如:489x85 如:128965-98542有什么口决及速算的方法的详细步骤?...
  14. HTML 简单日历制作方法
  15. 随心而行----我与计算机的缘分
  16. 重磅!腾讯优图29篇论文入选顶会ECCV 2022
  17. 概率论知识回顾(二):古典概型,几何概型
  18. C. Petya and Inequiations
  19. FairMOT训练测试自定义数据集
  20. torch.utils.data.WeightedRandomSampler采样

热门文章

  1. [转载] python numpy np.finfo()函数 eps
  2. Vue.js 学习笔记 五 常用的事件修饰符
  3. Ngnix中的fastcgi參数性能优化和解释
  4. Linux 防火墙 开放 端口 iptables
  5. JavaScript实现了网页的行为
  6. Oracle使用NLSSORT函数实现汉字的排序
  7. BestCoder Round #4 之 Miaomiao's Geometry(2014/8/10)
  8. 数据结构上机实践第八周项目4-字符串加密
  9. gnuplot 使用时遇到的问题
  10. Hexo为文章设置目录与标签的方法