首页 > 解决方案 > wordexp 和带空格的字符串

问题描述

我正在尝试在string包含 unix 文件路径的变量中展开变量。例如字符串是:

std::string path = "$HOME/Folder  With  Two  Spaces  Next  To  Each  Other".

这是我wordexp使用的代码:

#include <wordexp.h>
#include <string>
#include <iostream>

std::string env_subst(const std::string &path)
{
        std::string result = "";
        wordexp_t p;
        if (!::wordexp(path.c_str(), &p, 0))
        {
                if (p.we_wordc >= 1)
                {
                        result = std::string(p.we_wordv[0]);
                        for (uint32_t i = 1; i < p.we_wordc; ++i)
                        {
                                result += " " + std::string(p.we_wordv[i]);
                        }
                }
                ::wordfree(&p);
                return result;
        }
        else
        {
                // Illegal chars found
                return path;
        }
}

int main()
{
        std::string teststring = "$HOME/Folder  With  Two  Spaces  Next  To  Each  Other";
        std::string result = env_subst(teststring);
        std::cout << "Result: " << result << std::endl;
        return 0;
}

输出是:

Result: /home/nidhoegger/Folder With Two Spaces Next To Each Other

你看,虽然输入中的单词之间有两个空格,但现在只有一个空格。

有没有简单的方法来解决这个问题?

标签: c++linux

解决方案


您的代码删除路径中的双空格的原因是因为您的 for 循环仅在每个单词后添加一个空格,而不管实际的空格数如何。这个问题的一个可能的解决方案是事先找到路径字符串中的所有空格,然后将它们添加进去。例如,您可以使用如下内容:

std::string spaces[p.we_wordc];
uint32_t pos = path.find(" ", 0);
uint32_t j=0;

while(pos!=std::string::npos){

    while(path.at(pos)==' '){
    spaces[j]+=" ";
    pos++;
    }

    pos=path.find(" ", pos+1);
    j++;
}

使用 std::string::find 遍历您的路径并将空格存储在字符串数组中。然后,您可以将 for 循环中的行修改为

result += spaces[i-1] + std::string(p.we_wordv[i]);

添加适当数量的空格。


推荐阅读