获取分隔符为/的给定字符串的最后一个目录的文本

Getting the text of the last directory of a given string with the delimiters of /

本文关键字:最后一个 文本 字符串 分隔符 获取      更新时间:2023-10-16

给定一个URL(它是一个字符串),例如:

www.testsite.com/pictures/banners/whatever/

我希望能够获得URL中最后一个目录的字符(在这种情况下,它是"whatever",我还想删除斜杠)。最有效的方法是什么?

感谢您的帮助

#include <iostream>
#include <string>
std::string getlastcomponent(std::string s) {
  if (s.size() > 0 && s[s.size()-1] == '/')
    s.resize(s.size() - 1);
  size_t i = s.find_last_of('/');
  return (i != s.npos) ? s.substr(i+1) : s;
}
int main() {
  std::string s1 = "www.testsite.com/pictures/banners/whatever/";
  std::string s2 = "www.testsite.com/pictures/banners/whatever";
  std::string s3 = "whatever/";
  std::string s4 = "whatever";
  std::cout << getlastcomponent(s1) << 'n';
  std::cout << getlastcomponent(s2) << 'n';
  std::cout << getlastcomponent(s3) << 'n';
  std::cout << getlastcomponent(s4) << 'n';
  return 0;
}

获取长度并从最后一个字母开始推送每个字母(例如伪代码:

x = string.length()
while(X != 0)
{
CharVector.push(string.at(x)); 
x--;
if(string.at(x) == "") break;
}

然后你得到了复仇而不是什么。然后用这个功能交换:

string ReverseString( const string& word )
{
    std::string l_bla;
    bla.reserve(word.size());
    for ( string::size_type x = word.length ( ); x > 0; x-- )
    {
        l_bla += word.at ( x -1 );
    }
    return l_bla;
}

所以你得到了任何