C++中string常用截取字符串方法有哪些-创新互联

这篇文章主要介绍C++中string常用截取字符串方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

成都创新互联公司是专业的新和网站建设公司,新和接单;提供成都网站建设、成都网站设计,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行新和网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

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常用截取字符串方法有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联网站建设公司行业资讯频道!

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

文章题目:C++中string常用截取字符串方法有哪些-创新互联
当前网址:https://www.cdcxhl.com/article26/hpdcg.html

成都网站建设公司_创新互联,为您提供网站建设网站策划网站导航小程序开发外贸建站面包屑导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

手机网站建设