程序员伪程序员

C++字符串处理小结

2016-04-18  本文已影响3517人  linjinhe

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的数字和字符串相互转换的算法:

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的字符串算法

字符串大小写转换

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

#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

子串删除。

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);
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);
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

子串查找

例子:

#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

连接字符串

例子:

#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

替换字符串

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

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

trim_left()删除字符串左边的空白。
trim_right()删除字符串右边的空白。
trim()删除字符串左右两边的空白。
trim系列的copy版本。
trim_left_if()
trim_right_if()
trim_if()
trim_if系列的copy版本,如果`trim_left_copy_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

分割字符串

例子:

#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提供了三个类型三个算法来处理正则表达式:

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

例子

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

#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
上一篇 下一篇

猜你喜欢

热点阅读