c++ - 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
你看,虽然输入中的单词之间有两个空格,但现在只有一个空格。
有没有简单的方法来解决这个问题?
解决方案
您的代码删除路径中的双空格的原因是因为您的 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]);
添加适当数量的空格。
推荐阅读
- mysql - 我可以在 WampServer 上连接另一个本地 MySQL 服务吗?
- javascript - 编辑字符串数组,只保留值的第一个字母
- php - php 的 session_reset 可以用来重新加载修改过的会话吗?
- matlab - 使用迭代查找方程的根
- python - 使用 QToolBar 和 QListView 进行面包屑导航
- java - 使用 JavaFX 在覆盆子 PI 上构建 Maven 失败
- sql - 将数组传递给 PostgreSQL PL/pgSQL 函数
- pdf - centos7上的Ghostscript无法将pdf转换为jpg
- java - 按照推荐添加了 spring-boot-configuration-processor,但在 RoundDispatcher 中产生了 NoClassDefFoundError
- python - 如何比较python中的2个排序数字列表,其中每个对应元素不必完全匹配?