Search code examples
c++c++17std-filesystem

How can I erase first and last character in string?


This function returns an array of strings with a list of files in a folder. It looks like this:

"folder//xyz.txt"

How can I make it look like this?

folder//xyz.txt

Its the same but without "".

vector<string> list_of_files(string folder_name)                           
{
    vector<string> files;
    string path = folder_name;

    for (const auto& entry : fs::directory_iterator(path))      
    { 
        stringstream ss;
        ss << entry.path();        //convert entry.path() to string
        string str = ss.str();                  
                    
        files.push_back(ss.str());
    }  

    return files;
}

Solution

  • Erasing the first and last characters of a string is easy:

    if (str.size() >= 1)
       str.erase(0, 1);   // from 1st char (#0), len 1; bit verbose as not designed for this
    
    if (str.size() >= 1)
       str.pop_back();    // chop off the end
    

    Your quotes have come from inserting the path to a stream (quoted is used to help prevent bugs due to spaces down the line).

    Fortunately, you don't need any of this: as explored in the comments, the stringstream is entirely unnecessary; the path already converts to a string if you ask it to:

    vector<string> list_of_files(string folder_name)
    {
        vector<string> files;
    
        for (const auto& entry : fs::directory_iterator(folder_name))
            files.push_back(entry.path().string());
    
        return files;
    }