在标准 C++ 中,用于处理字符串的是 std::string
类,它提供很多字符串操作,包括查找指定字符或子串的函数。 尽管 std::string
囊括了百余函数,是标准 C++ 中最为臃肿的类之一,然而却并不能满足很多开发者在日常工作中的需要。
在进入正题之前,有必要先审视下区域设置的问题,区域设置在标准 C++ 中封装了文化习俗相关的内容,包括货币符号,日期时间格式, 分隔整数部分与分数部分的符号(基数符)以及多于三个数字时的分隔符(千位符)。C++ 标准中在 locale
文件中定义了类 std::locale
,全局区域设置可以使用类 std::locale
中的静态函数 global()
改变。例如:
#include <locale>
#include <iostream>
int main()
{
std::locale::global(std::locale("German"));
std::locale loc;
std::cout << loc.name() << std::endl;
}
1、字符串算法库 Boost.StringAlgorithms
Boost C++ 字符串算法库 Boost.StringAlgorithms 提供了很多字符串操作函数。 字符串的类型可以是 std::string
, std::wstring
或任何其他模板类 std::basic_string
的实例。头文件 boost/algorithm/string.hpp
包括了所有字符串操作的头文件,所以使用时,只需包含 boost/algorithm/string.hpp即可。先介绍几个API:
- boost::algorithm::to_upper_copy(str):根据字符串str生成其大写方式后返回,但并不改变str
- boost::algorithm::to_lower_copy(str):根据字符串str生成其小写方式后返回,但并不改变str
- boost::algorithm::to_upper(str):将字符串str转换成大写方式。
- boost::algorithm::to_lower (str):将字符串str转换成小写方式。
- boost::algorithm::erase_first_copy(str, "i"):删除字符串str中字符i首次出现的位置,返回删除后的字符串
- boost::algorithm::erase_nth_copy(str, "i", 1):删除字符串str中字符i第2次出现的位置,返回删除后的字符串
- boost::algorithm::erase_last_copy(str, "i"):删除字符串str中字符i最后一次出现的位置,返回删除后的字符串
- boost::algorithm::erase_all_copy(str, "i"):删除字符串str中所有的字符i,返回删除后的字符串
- boost::algorithm::erase_head_copy(str, 5):删除字符串前5个字符,返回删除后的字符串
- boost::algorithm::erase_tail_copy(str, 8):删除字符串str最后8个字符,返回删除后的字符串