如何删除字符串中的第一个和最后一个字符?

How can I erase first and last character in string?

此函数 returns 一个包含文件夹中文件列表的字符串数组。它看起来像这样:

"folder//xyz.txt"

我怎样才能让它看起来像这样?

folder//xyz.txt

相同但没有""

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;
}

删除字符串的第一个和最后一个字符很容易:

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

您的引用来自插入流的路径 (quoted is used to help prevent bugs due to spaces down the line)。

幸运的是,您不需要这些:正如评论中所探讨的那样,stringstream 是完全没有必要的;如果您要求路径已经转换为字符串:

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;
}