string常用擷取字串方法有很多,但是配合使用以下兩種,基本都能滿足要求:
find(string strsub, npos);
find_last_of(string strsub, npos);
其中strsub是需要尋找的子字串,npos為查詢起始位置。找到返回子字串首次出現的位置,否則返回-1;
注:(1)find_last_of的npos為從末尾開始尋找的位置。
(2)下文中用到的strsub(npos,size)函式,其中npos為開始位置,size為擷取大小
例1:直接查詢字串中是否具有某個字串(返回"2")
std::string strpath = "e:\\資料\\2018\\2000座標系\\a.shp"
int a = 0;
if (strpath.find("2018") == std::string::npos)
else
return a;
例2:查詢某個字串的字串(返回「e:」)
std::string strpath = "e:\\資料\\2018\\2000座標系\\a.shp"
int npos = strpath.find("\\");
if(npos != -1)
return strpath;
例3:查詢某個字串中某兩個子字串之間的字串(返回「2000座標系」)
std::string strpath = "e:\\資料\\2018\\2000座標系\\a.shp"
std::string::size_type npos1 = std::string::npos;
std::string::size_type npos2 = std::string::npos;
npos1 = strpath.find_last_of("\\");
npos2 = strpath.find_last_of("\\", npos1 - 1);
if(npos1 !=-1 && npos2 != -1)
return strpath;
提高:遞迴獲取路徑名中的子目錄
//獲取路徑名中的子目錄:strpath為路徑名,strsubpath為輸出的子目錄,
nsearch為從尾向前檢索的級別(預設為1級)
bool _getsubpath(std::string& strpath,std::string& strsubpath, int nsearch)
return true;
}int main()
if(_getsubpath(strpath, strsubpath, 2)
}
C string 擷取字串
string str 123abc456 int i 3 1 取字串的前i個字元 str str.substring 0,i or str str.remove i,str.length i 2 去掉字串的前i個字元 str str.remove 0,i or str str.substring i...
CString擷取字串方法
c中cstring型別好像沒有像string.substring parame 這樣類似的函式來從字串中直接分離子串,但是我們可以借助cstring的幾個函式來實現。在cstring中有find delete left right mid 就可以實現分離子串的目的了。intfind tchar ch...
CString 擷取字串全攻略
函式在比較時不區分大小寫 引數 為要和物件比較的字串,也可以為cstring物件 返回值 如果兩個字串一樣則返回0 intstrcmp constchar constchar string2 注 函式在比較時區分大小寫 引數 為要和物件比較的字串 返回值 string1 string2返回0 str...