C++中string常用截取字符串方法是什么

本文小編為大家詳細(xì)介紹“C++中string常用截取字符串方法是什么”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C++中string常用截取字符串方法是什么”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

成都創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站設(shè)計、成都做網(wǎng)站、會同網(wǎng)絡(luò)推廣、微信小程序開發(fā)、會同網(wǎng)絡(luò)營銷、會同企業(yè)策劃、會同品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;成都創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供會同建站搭建服務(wù),24小時服務(wù)熱線:18982081108,官方網(wǎng)址:www.muchs.cn

string常用截取字符串方法有很多,但是配合使用以下兩種,基本都能滿足要求:

find(string strSub, npos);

find_last_of(string strSub, npos);

其中strSub是需要尋找的子字符串,npos為查找起始位置。找到返回子字符串首次出現(xiàn)的位置,否則返回-1;

注:

(1)find_last_of的npos為從末尾開始尋找的位置。

(2)下文中用到的strsub(npos,size)函數(shù),其中npos為開始位置,size為截取大小

例1:直接查找字符串中是否具有某個字符串(返回"2")

std::string strPath = "E:\\數(shù)據(jù)\\2018\\2000坐標(biāo)系\\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:\\數(shù)據(jù)\\2018\\2000坐標(biāo)系\\a.shp"
int nPos = strPath.find("\\");
if(nPos != -1)
{
  strPath = strPath.substr(0, nPos);
}
return strPath;

例3:查找某個字符串中某兩個子字符串之間的字符串(返回“2000坐標(biāo)系”)

std::string strPath = "E:\\數(shù)據(jù)\\2018\\2000坐標(biāo)系\\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為從尾向前檢索的級別(默認(rèn)為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:\\數(shù)據(jù)\\2018\\2000坐標(biāo)系\\a.shp";
  std::string strSubPath = "";
  if(_GetSubPath(strPath, strSubPath, 1)
  {
    printf(“返回'a.shp'”);
  }
  if(_GetSubPath(strPath, strSubPath, 2)
  {
    printf(“返回'2000坐標(biāo)系'”);
  }
}

讀到這里,這篇“C++中string常用截取字符串方法是什么”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

文章題目:C++中string常用截取字符串方法是什么
網(wǎng)站地址:http://www.muchs.cn/article46/gceihg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、網(wǎng)站內(nèi)鏈網(wǎng)站維護、自適應(yīng)網(wǎng)站、網(wǎng)站收錄

廣告

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

營銷型網(wǎng)站建設(shè)