• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

详解C++ string常用截取字符串方法

c++ 搞代码 4年前 (2022-01-06) 66次浏览 已收录 0个评论

这篇文章主要介绍了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 && np<a style="color:transparent">来源gao($daima.com搞@代@#码网</a>os2 != -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常用截取字符串方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:详解C++ string常用截取字符串方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址