使用boost庫的字符串處理之前,需要進行區域設置。類:std::locale,每個C++程序自動擁有一個此類的實例,不能直接訪問全局區域設置。
全局區域設置可以使用類std::locale中的靜態函數global()改變。
#include <locale> #include <iostream> int main() { std::locale::global(std::locale("German")); std::locale loc; std::cout << loc.name() << std::endl; return 0; }
靜態函數global()接受一個類型為std::locale的對象作為其唯一的參數。
正則表達式庫 Boost.Regex
boost::regex 用於定義一個正則表達式庫
boost::smatch可以保存搜索結果
#include <boost/regex.hpp> #include <locale> #include <iostream> int main() { std::locale::global(std::locale("German")); std::string s = "Boris Schaling"; boost::regex expr("\\w+\\s\\w+");
std::cout << boost::regex_match(s, expr) << std::endl;
return 0;
}
boost::regex_match()用於字符串與正則表達式的比較,字符串匹配正則表達式時返回true。
下面介紹一下boost string常用的算法接口:
1. case conversiion to_upper() 將輸入字符串轉換成大寫。 to_upper_copy() 輸入字符串不變,返回值為轉換成大寫的字符串。 to_lower() 將輸入字符串轉換成小寫。 to_lower_copy() 輸入字符串不變,返回值為轉換成小寫的字符串。
2. trimming trim_left() 將輸入字符串左邊的空格刪除。 trim_left_copy() 輸入字符串不變,返回去除左邊空格的字符串。 trim_left_if() 將輸入字符串左邊符合條件的字符去除。trim_left_if("12hello", is_digit()), 輸出 hello trim_left_copy_if() 輸入字符串不變,意思同上。 trim_right() 意思同left差不多。刪除右邊的空格 trim_right_if() trim_right_copy() trim_right_copy_if() trim() 刪除首尾兩端的空格。 trim_if() trim_copy() trim_copy_if()
3. predicates bool starts_with(input, test) 判斷input是否以test為開端。 bool istarts_with(input, test) 判斷input是否以test為開端,大小寫不敏感。 bool ends_with(input, test) 判斷input是否以test結尾。 bool iends_with(input, test) 判斷input是否以test結尾, 大小寫不敏感。 bool contains(input, test) 判斷test是否在input里。 bool icontains(input, test) 判斷test是否在input里,大小寫不敏感。 bool equals(input, test) 判斷input和test是否相等。 bool iequals(input, test) 判斷input和test是否相等, 大小寫不敏感。 bool lexicographical_compare() 按字典順序檢測input1是否小於input2。 bool ilexicographical_compare() 按字典順序檢測input1是否小於input2, 大小寫不敏感。 bool all() 檢測輸入的每個字符是否符合給定的條件。
4. find algorithms iterator_range<string::iterator> find_first(input, search) 從input中查找第一次出現search的位置。 iterator_range<string::iterator> ifind_first(input, search) 從input中查找第一次出現search的位置,大小寫不敏感。 iterator_range<string::iterator> find_last(input, search) 從input中查找最后一次出現search的位置。 iterator_range<string::iterator> ifind_last(input, search) 從input中查找最后一次出現search的位置,大小寫不敏感。 iterator_range<string::iterator> find_nth(input, search, n) 從input中查找第n次(n從0開始)出現search的位置。 iterator_range<string::iterator> ifind_nth(input, search, n) 從input中查找第n次(n從0開始)出現search的位置,大小寫不敏感。 iterator_range<string::iterator> find_head(input, n) 獲取input開頭n個字符的字串。 iterator_range<string::iterator> find_tail(input, n) 獲取input尾部n個字符的字串。
iterator_range<string::iterator> find_token()