详解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 || pty())
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常⽤截取字符串⽅法详解整合,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。