C++中string常用截取字符串方法有哪些

這篇文章主要介紹C++中string常用截取字符串方法有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

創(chuàng)新互聯于2013年成立,先為鳳翔等服務建站,鳳翔等地企業(yè),進行企業(yè)商務咨詢服務。為鳳翔企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。

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("\\");
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("\\");
nPos2 = strPath.find_last_of("\\", 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("\\");
	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常用截取字符串方法有哪些”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯行業(yè)資訊頻道!

本文題目:C++中string常用截取字符串方法有哪些
URL鏈接:http://bm7419.com/article28/jjcpjp.html

成都網站建設公司_創(chuàng)新互聯,為您提供建站公司、網站內鏈軟件開發(fā)、網站排名、微信公眾號、網站導航

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯

h5響應式網站建設