国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

詳解C++ string常用截取字符串方法

2020-01-26 13:28:08
字體:
來源:轉載
供稿:網友

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){	a = 1;}else{	a = 2;}return a;

例2:查找某個字符串的字符串(返回“E:”)

std::string strPath = "E://數據//2018//2000坐標系//a.shp"int nPos = strPath.find("http://");if(nPos != -1){  strPath = strPath.substr(0, nPos);}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("http://");nPos2 = strPath.find_last_of("http://", nPos1 - 1);if(nPos1 !=-1 && npos2 != -1){  strPath = strPath.substr(nPos2 + 1, nPos1 - nPos2 - 1);}return strPath;

提高:遞歸獲取路徑名中的子目錄

//獲取路徑名中的子目錄:strPath為路徑名,strSubPath為輸出的子目錄, nSearch為從尾向前檢索的級別(默認為1級) bool _GetSubPath(std::string& strPath,std::string& strSubPath, int nSearch){		if (-1 == nSearch || strPath.empty())		return false;	std::string::size_type nPos1 = std::string::npos;	nPos1 = strPath.find_last_of("http://");	if (nPos1 != -1)	{		strSubPath = strPath.substr(nPos1 + 1, strPath.length() - nPos1);		int nNewSearch = nSearch > 1 ? nSearch - 1 : -1;		_GetSubPath(strPath.substr(0, nPos1), strSubPath, nNewSearch);	}	return true;} int main(){  std::string strPath = "E://數據//2018//2000坐標系//a.shp";  std::string strSubPath = "";  if(_GetSubPath(strPath, strSubPath, 1)  {    printf(“返回'a.shp'”);  }  if(_GetSubPath(strPath, strSubPath, 2)  {    printf(“返回'2000坐標系'”);  }}

以上所述是小編給大家介紹的C++ string常用截取字符串方法詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临海市| 东台市| 南召县| 浦县| 巴彦淖尔市| 朔州市| 枞阳县| 樟树市| 卢湾区| 台中市| 玉林市| 策勒县| 林甸县| 镇江市| 中江县| 莱州市| 崇左市| 平定县| 富民县| 二手房| 安国市| 长治市| 贵南县| 六盘水市| 合阳县| 福建省| 阳谷县| 鄂托克前旗| 乌苏市| 高唐县| 临桂县| 阳城县| 海阳市| 十堰市| 荥经县| 眉山市| 江北区| 湘阴县| 察哈| 印江| 永泰县|