1. 程式人生 > >[C/C++]_[初級]_[Windows上的字串處理實用函式]

[C/C++]_[初級]_[Windows上的字串處理實用函式]

場景

1.C/C++開發過程中, C字串函式或者std::string是相當實用的了, 可以查詢,擷取,移除等, 但是一般都是移除指定的一個字元而不是字串, 移除還是大小寫敏感的. 當然也可以用正則表示式來移除或查詢,
但是總也得3-4行程式碼吧.

2.std::string 不但可以儲存字串, 還可以儲存任意位元組資料. 但是在查詢,替換,移除字串上也是和C差不多,
如果要在一段文本里查詢某個姓名是否存在,那麼就得把這個文字先轉換為大寫, 之後再把要查詢的姓名轉換為大寫, 之後再查詢, 相當麻煩.

說明

1.Windows Desktop程式設計裡的Shell庫裡就有相關的字串處理函式, 可以說是對C/C++字串不足的補充, 非常實用, 比如大小寫不敏感的查詢,移除前後空格, 把數值轉換為容量字串, 大小寫不敏感的字串比較.

2.這裡摘取了部分常用的路徑處理函式, 還有其他函式請參考Shell String Handling Functions.

程式碼


#include "Shlwapi.h"

void TestShellStringFunction()
{
    // ChrCmpI
    std::cout << "============= 比較兩個字串,大小寫不敏感, 而strcmp是大小寫敏感的 =============" << std::endl;
    auto Tom = L"Tom";
    auto tom = L"tom";
    auto Ton = L"ToN"
; if(StrCmpI(Tom,tom) == 0) std::wcout << Tom << " and " << tom << L" is same." << std::endl; if(StrCmpI(Tom,Ton) < 0) std::wcout << Tom << " smaller than " << Ton << std::endl; // StrStrI std::cout << "============= 查詢子字串是否存在,大小寫不敏感,而strstr是大小寫敏感的 ============="
<< std::endl; // 常用在搜尋框查詢處理,比較實用,這樣就不需要把原字串和子字串轉換為大寫再去搜索. auto text = L"I am a cloud, I am a AI, Configuration for you. thank you."; auto sub = L"ai"; if(StrStrI(text,sub)) std::wcout << text << " has substring " << sub << std::endl; std::cout << "============= 移除字串前後指定字元,比如空格和tab =============" << std::endl; // 這個應該是Win最快的做法, 不需要自己寫函式來移除前後空格了. wchar_t article[256] = L" hello world. "; wchar_t trim[] = {32,9,L'\0'}; StrTrim(article,trim); std::wcout << L"|" <<article << L"|" << std::endl; // StrFormatByteSizeW std::cout << "============= 把數值轉換為容量大小字串,也不需要自己去寫了,省事. =============" << std::endl; // 使用系統的函式,可以避免當前系統基數是以1000還是1024來識別的了. if(StrFormatByteSizeW(21341231234,article,256)) std::wcout << L"size is:" << article << std::endl; }

輸出:

============= 比較兩個字串,大小寫不敏感, 而strcmp是大小寫敏感的 =============
Tom and tom is same.
Tom smaller than ToN
============= 查詢子字串是否存在,大小寫不敏感,而strstr是大小寫敏感的 =========
====
I am a cloud, I am a AI, Configuration for you. thank you. has substring ai
============= 移除字串前後指定字元,比如空格和tab =============
|hello world.|
============= 把數值轉換為容量大小字串,也不需要自己去寫了,省事. ============
=
size is:19.8 GB

參考

Shell String Handling Functions