C++ Boost 字符串处理库

Boost 库是一个由C/C++语言的开发者创建并更新维护的开源类库,其提供了许多功能强大的程序库和工具,用于开发高质量、可移植、高效的C应用程序。Boost库可以作为标准C库的后备,通常被称为准标准库,是C标准化进程的重要开发引擎之一。使用Boost库可以加速C应用程序的开发过程,提高代码质量和性能,并且可以适用于多种不同的系统平台和编译器。Boost库已被广泛应用于许多不同领域的C++应用程序开发中,如网络应用程序、图像处理、数值计算、多线程应用程序和文件系统处理等。
Boost库官网> https://www.boost.org/
者可自行去官方下载对应特定编译器的二进制文件,在官方网站页面中选中More Downloads... 下载页面,并点击Prebuilt windows binaries则可打开二进制预编译版本的对应页面。

此时读者可根据自己编译器的版本选择适合于自己的库,此处笔者使用的是Visual Studio 2022编译器,所以此处选中的是1.85.0目录下的bootstrap.bat安装包。
在安装完成后,读者可自行打开安装目录,该目录中我们所需要配置的选项只有1个,首先读者需要在VS中引入boost_1_85_0目录1如下图所示则是正常引用后的配置参数;

在C语言的早期版本中,对于字符串和文本的处理一直都是最为薄弱的,直到C++98规范的推出才勉强增加了一个std::string的类,虽然在一定程度上弥补了字符串处理的不足,但仍然缺少一些更为强大和丰富的字符串处理和操作工具。
随着Boost库的推出和广泛应用,该库内置了多种用于字符串和文本处理的强大工具,为C程序员提供了强大的库和更全面的支持。Boost库中的字符串处理工具包括字符串分割、替换、转换、截断以及正则表达式等功能。使用Boost库,C程序员现在可以轻松地处理字符串和文本数据,开发更加高效和强大的C应用程序。
1.1 字符串格式转换
lexical_cast是Boost库中用于类型转换的一种强大的工具。它可以将一个类型的对象转换为另一个类型,例如将字符串类型的数据转换为数字类型的数据。它简化了类型转换的代码,并提供了一些错误检查,以确保转换的安全性。在使用lexical_cast时,程序员只需指定需要转换的源数据类型和目标数据类型即可,在大多数情况下,可以自动完成转换,lexical_cast是字符串格式转换的一个重要工具,非常适用于将字符串和数字类型之间进行快速而安全的转换。

但读者需要注意,lexical_cast并不支持自定义类型的转换,例如自定义类或结构体。如果需要进行自定义类型的转换,需要使用Boost库中的其他工具或者自行编写转换函数。

点击查看代码
#include <iostream>
#include <string>
#include <boost\lexical_cast.hpp>

using namespace std;
using namespace boost;

int main(int argc, char * argv[])
{
  string str[3] = { "100", "102", "3.14159" };

  // 字符串转换为数值类型
  std::cout << "字符串转为整数: " << lexical_cast<int>(str[0]) << std::endl;
  std::cout << "字符串转为长整数: " << lexical_cast<long>(str[1]) << std::endl;
  std::cout << "字符串转为浮点数: " << lexical_cast<float>(str[2]) << std::endl;

  // 数值类型转化为字符串
  std::cout << "数值转为字符串: " << lexical_cast<string>(100) << std::endl;
  std::cout << "十六进制转为十进制: " << lexical_cast<string>(0x10) << std::endl;

  // 转换后赋值给变量
  try{
    int number = lexical_cast<int>(str[0]);
    std::cout << "转换后赋值给变量: " << number << std::endl;
  }
  catch(bad_lexical_cast&){
    std::cout << "转换失败抛出异常." << std::endl;
  }

  system("pause");
  return 0;
}

此外C++默认库中同样提供了一些可实现字符串与数值之间转换的函数,这些函数包括了atoi,itoa,atof,gcvt,这些内置函数库通常不具有lexical_cast函数所提供的错误检查和异常处理机制,因此在使用时还需要特别注意程序的输出结果。
点击查看代码
int main(int argc, char* argv[])
{
	string str[3] = { "100","102","3.14159" };
	int inter[3] = { 100,45,7 };

	//atoi
	int number_a = atoi(str[0].c_str());
	cout << "字符串转为整数:" << number_a << endl;

	// itoa
	char buf1[64] = { 0 };
	_itoa(inter[0], buf1, 16);
	cout << "将inter[0]转换为16进制并放入buf中:" << buf1 << endl;

	// atof
	double number_b = atof(str[2].c_str());
	cout << "将字符串转为双精度:" << number_b << endl;

	//gcvt
	char buf2[64] = { 0 };
	char* number_c = _gcvt(3.54655, 3, buf2);
	cout << "将浮点数转为字符串,保留两位(四舍五入):" << buf2 << endl;

	//sprintf
	char buf3[64] = { 0 };
	int  number_d = 10345;

	sprintf(buf3, "%d", number_d);
	cout << "将number_d中的整数转为字符串:" << buf3 << endl;

	system("pause");
	return 0;
}

1.2字符串格式输出

format是Boost库中用于格式化字符串的工具。它提供了一种简单、安全和灵活的方式来生成格式化字符串。并支持广泛的格式标识符和
操作符。使用boost::format,程序员可以在字符串中插入变量,数字等内容,并指定它们的格式。在boost::format中,执行的格式化
操作使用类似于pritf中格式化字符串的方式,以"{}"形式表示变量的位置,并使用占位符指定变量的类型和格式。例如,以下示例利用
boost::format分别实现了四种不同的格式化方法:

点击查看代码
#include<iostream>
#include<string>
#include<boost/format.hpp>
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
	//第一种方式:直接填充字符串
	boost::format fmtA("姓名:%s ->年龄:%d->性别:%s");
	fmtA % "lyshark";
	fmtA % 22;
	fmtA % "男";
	string str = fmtA.str();
	cout << "第一种输出:" << str << endl;

	//第二种方式:拷贝的使用
	boost::format fmtB("姓名:%s ->年龄:%d ->性别:%s");
	cout << "第二种输出:" << format(fmtB) % "lyshark" % 23 % "男" << endl;

	//第三种方式:拷贝后强转
	string str_format = boost::str(boost::format("%d.%d.%d.%d") % 192. % 168. % 1. % 100);
	cout << "第三种输出:" << str_format << endl;


	// 第四种方式:格式化输出
	// %|10s| 输出宽度为10,不足补空格
	// %|06X| 输出宽度为7的大写16进制整数
	boost::format str_tmp("%|10s|\n %|07X|\n");
	str_tmp % "lyshark" % 100;
	string str_format_B = boost::str(str_tmp);
	cout << "第四种输出" << str << str_format_B << endl;
	system("pause");
	return 0;
}

1.3字符串大小写转换

字符串大小写转换可使用to_upper()和to_lower()这两个函数,这两个函数都是Boost库中的字符串处理函数,它们与C++标准库的
同名函数功能类似,但支持更广泛的字符集以满足更多应用场景的需求。boost:to_upper()函数将制定字符串中的字母字符全部转换
为大写格式,并返回转换后的新字符串,boost::to_lower()函数则将指定字符串的字母字符全部转为小写格式,并返回转换后的新
字符串。
以下是使用boost::to_upper()和boost::to_lower()进行字符串大小写转换的示例:

点击查看代码
#include<iostream>
#include<Windows.h>
#include<string>
#include<boost/format.hpp>
#include<vector>
#include<boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
	vector<string> str_array = { "hello","lyshark","welcome","to","my","blog" };
	cout << "str_array.size()" << str_array.size() << endl;
	//循环转换为大写,to_upper_copy不会影响原生字符串
	for (int x = 0; x < str_array.size(); x++)
	{
		string item = to_upper_copy(str_array[x]);
		cout << "转换拷贝:" << item << endl;
	}
	cout << "原始字符串不受影响:" << str_array[1] << endl;

	//如果使用to_upper则会直接修改原生字符串
	for (int x = 0; x < str_array.size(); x++)
	{
		to_upper(str_array[x]);
	}
	cout << "原始字符串受影响:" << str_array[1] << endl;


	system("pause");
	return 0;

}

1.4字符串判断与测试

starts_with()和ends_with()也是Boost库中的字符串处理函数。这两个函数分别用于检查一个字符串是否以指定字符串开头或结尾,
而contains()则用于测试字符串的属性。
boost::starts_with接收两个参数,第一个参数是待检查的字符串,第二个参数是被检查作为开头的字符串,返回一个bool值表示
原始字符串是否以目标字符串开头。
boost::ends_with也是接收两个参数,第一个参数是待检查的字符串,第二个参数是被检查作为结尾的字符串,返回一个bool值表示
原始字符串是否以目标字符串结尾。以下是boost::starts_with()和boost::ends_with()两个函数的示例:

点击查看代码
#include<iostream>
#include<Windows.h>
#include<boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
	string str[6] = { "hello lyshark","hello LyShark","readme.txt","ABC","FCE","lyshark" };
	cout << "大小写不敏感判断后缀:" << iends_with(str[0], "lyshark") << endl;
	cout << "大小写敏感判断前缀:" << starts_with(str[1], "Hello") << endl;

	cout << "测试str[0]里面是否包含str[5]"<<contains(str[0],str[5])<<endl;
	cout << "测试前5个字母是否为小写:" << all(str[0].substr(0, 5), is_lower()) << endl;
	cout << "测试前2个字符是否为字母:" << all(str[1].substr(0, 2), is_alpha()) << endl;
	system("pause");
	return 0;
}

1.5 字符串修正与裁剪

boost::replace_first_copy()、boost::replace_last_copy()、boost::trim()、boost::trim_left()
和boost::trim_right()都是Boost库中的字符串处理函数。
replace_first_copy用于将字符串中第一个匹配的字符串替换为新字符串,返回替换后的新字符串并不改变原字符串。
replace_last_copy函数用于将字符串中最后一个匹配的子字符串替换为新的字符串,同样返回替换后的新字符串且不改变原字符串。
trim() trim_left和trim_right用于去除字符串两端的空格或指定的字符,返回处理后的新字符串并不改变原字符串。

点击查看代码
#include<iostream>
#include<string>
#include<vector>
#include<boost/foreach.hpp>
#include<boost/algorithm/string.hpp>
#include<boost/format.hpp>
using namespace std;
using namespace boost;
int main(int argc, char* argv[])
{
	string str[6] = { "hello lyshark","hello LyShark","readme.txt","ABC","FCE","lyshark" };

	//字符串替换:替换开头/结尾 字符串hello为lyshark
	cout << replace_first_copy(str[0], "hello", "lyshark") << endl;
	cout << replace_last_copy(str[0], "hello", "lyshark") << endl;

	//字符串删除:删除字符串结尾的.txt并将其开头部分转换为大写
	vector<char> v(str[2].begin(), str[2].end());
	vector<char> v2 = to_upper_copy(erase_first_copy(v, ".txt"));

	for (auto x : v2)
		cout << x;
	cout << endl;

	//字符串修剪:去除字符串中的空格或-
	boost::format fmt("|%s|\n");
	string my_string_a = "    hello   lyshark  ";
	cout << "删除两端空格:" << fmt % trim_copy(my_string_a) << endl;
	cout << "删除左端空格: " << fmt % trim_left_copy(my_string_a) << endl;
	cout << "删除右端空格:" << fmt % trim_right_copy(my_string_a) << endl;

	string s = "--lyshark--";
	cout << "删除左侧所有的-:" << trim_left_copy_if(s, is_any_of("-")) << endl;
	cout << "删除右侧所有的-:" << trim_right_copy_if(s, is_any_of("-")) << endl;
	cout << "删除两侧所有的-:" << trim_copy_if(s, is_any_of("-")) << endl;

	//字符串修剪:去除字符串中的特殊符号
	string my_string_b = "2021 happy new Year !!!";
	cout << "删除左端数字:" << fmt % trim_left_copy_if(my_string_b, is_digit()) << endl;
	cout << "删除右边标点:" << fmt % trim_right_copy_if(my_string_b, is_punct()) << endl;
	cout << "删除两端(标点|数字|空格):" << trim_copy_if(my_string_b, is_punct() || is_digit() || is_space()) << endl;
	system("pause");
	return 0;
}
未完待续,转自

https://www.cnblogs.com/LyShark/p/17639539.html

posted @ 2024-07-08 11:10  阳光天气  阅读(36)  评论(0编辑  收藏  举报