Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created November 22, 2023 08:33
Show Gist options
  • Save juanfal/69ea8474651b663515087071f39f59c4 to your computer and use it in GitHub Desktop.
Save juanfal/69ea8474651b663515087071f39f59c4 to your computer and use it in GitHub Desktop.
file name from path
// filename.cpp
// juanfc 2022-11-24
//
#include <iostream>
using namespace std;
string fileName(string path);
string fileName2(string path);
int main()
{
string substr(string s, int pos, int len);
cout << fileName("/Users/me/Desktop/fileName.cpp") << endl;
cout << fileName2("/Users/me/Desktop/fileName.cpp") << endl;
return 0;
}
string fileName(string path)
{
int i = path.length();
while (i >= 0 and path[i] != '/')
--i;
return path.substr(i+1, path.length());
}
string substr(string s, int pos, int len);
string fileName2(string path)
{
int i = path.length()-1;
while (i >= 0 and path[i] != '/')
--i;
return substr(path, i+1, path.length()-i-1);
// return substr(path, i+1, path.length());
}
string substr(const string s, int pos, int len)
{
string r;
int i = pos;
while (i < s.length() and i-pos < len)
r += s[i++];
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment