温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2022-04-14 16:53:05 来源:亿速云 阅读:3845 作者:iii 栏目:编程语言

本文小编为大家详细介绍“C++中string常用截取字符串方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“C++中string常用截取字符串方法是什么”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

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常用截取字符串方法是什么”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI