1. 程式人生 > >Boost(五)——字串處理(一):字串操作

Boost(五)——字串處理(一):字串操作

由於這一章內容過多,我將採用三個小章,精簡原文三個小部分內容。

區域設定:

setlocale(LC_ALL,“”)
locale::global(std::locale("German")); //設定全域性區域德語環境

字串操作:

一、將字串所有字元轉成大寫

boost::algorithm::to_upper("")//自身轉化
boost::algorithm::to_upper_copy("")//返回轉化的結果,自身不轉化

轉成小寫

boost::algorithm::to_lower("")
boost::algorithm::to_lower_copy("")

二、刪除特定字串

boost::algorithm::erase_first_copy(s,"") //從s刪除第一個匹配的字串
boost::algorithm::erase_nth_copy(s,"",n) //從s刪除第n個匹配的字串
boost::algorithm::erase_last_copy(s, "") //從s刪除最後匹配的字串
boost::algorithm::erase_all_copy(s, "") //從s刪除所有匹配的字串
boost::algorithm::erase_head_copy(s, n) //從s刪除前n個字元
boost::algorithm::erase_tail_copy(s, n) //從s刪除後n個字元

三、查詢特定字串

與二相同使用方法,將erase替換成find即可。

四、字串迭代器

儲存字串每個字元。

boost::iterator_range<string::iterator> r = boost::algorithm::find_first(s,"");
for_each(r.begin(), r.end(), [](char c){cout << c << endl;});

五、新增字串

vector<string> v;
v.push_back("hello");
v.push_back("world");
boost::algorithm::join(v, ""); //根據第二個引數將這些字串連線起來。

六、替換字串

boost::algorithm::replace_first_copy(s,"","") //從s替換第一個匹配的字串成第三個引數
boost::algorithm::replace_nth_copy(s,"",n,"") //從s替換第n個匹配的字串成第四個引數
boost::algorithm::replace_last_copy(s, "","") //從s替換最後匹配的字串成第三個引數
boost::algorithm::replace_all_copy(s, "","") //從s替換所有匹配的字串成第三個引數
boost::algorithm::replace_head_copy(s, n,"") //從s替換前n個字元成第三個引數
boost::algorithm::replace_tail_copy(s, n,"") //從s替換後n個字元成第三個引數

七、裁剪字串

自動裁剪:(空格或者結束符)

boost::algorithm::trim_left_copy(s)//去除左邊
boost::algorithm::trim_right_copy(s)//去除右邊
boost::algorithm::trim_copy(s)//上兩個效果合

特定裁剪:指定字串裁剪

boost::algorithm::trim_left_copy_if(s, boost::algorithm::is_any_of(""))//去除左邊
boost::algorithm::trim_right_copy_if(s, boost::algorithm::is_any_of(""))//去除右邊
boost::algorithm::trim_copy_if(s, boost::algorithm::is_any_of(""))//上兩個效果合

函式boost::algorithm::is_digit() 返回的謂詞在字元為數字時返回布林值 。

裁剪謂詞是數字的字串:

boost::algorithm::trim_left_copy_if(s, boost::algorithm::is_digit())//去除左邊
boost::algorithm::trim_right_copy_if(s, boost::algorithm::is_digit())//去除右邊
boost::algorithm::trim_copy_if(s, boost::algorithm::is_digit())//上兩個效果合

八、比較字串

boost::algorithm::starts_with(s, "")//比較開頭
boost::algorithm::ends_with(s, "")//比較結尾
boost::algorithm::contains(s,"" )//比較是否存在
boost::algorithm::lexicographical_compare(s,"")/比較區間是否小於第二個引數

返回為bool型 

九、分割字串

boost::algorithm::split(s, 謂詞);

謂詞:判定分割點

例如:boost:algorithm::is_space() //在每個空格字元處分割字串

十、大小寫忽略函式

一般是上述函式原型前有i區分

例如 boost::algorithm::erase_all_copy() 對應 boost::algorithm::ierase_all_copy()。