c语言中截取字符串 sub,详解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常用截取字符串方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值