单词exp和带空格的字符串
wordexp and strings with spaces
我正在尝试扩展包含 unix 文件路径的string
中的变量。例如,字符串为:
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
你看,虽然输入中的单词之间有两个空格,但现在只有一个空格。
有没有简单的方法可以解决这个问题?
代码删除路径中的双空格的原因是,对于每个单词后只添加一个空格,而不管实际的空格数如何。此问题的一个可能的解决方案是事先找到路径字符串中的所有空格,然后将它们添加进来。例如,您可以使用如下内容:
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]);
以添加适当数量的空格。
如果要在异常命名的文件中保留空格,请将其括在大括号中:std::string teststring = ""~/filename with spaces"";
.但是注意原始字符串中有多少空格是没有意义的,因为您必须跳过成对的"
并基本上重做wordexp()
的功能。在命令中留下多个空格没有多大意义:ls -al
与ls -al
完全相同,因此修剪是合理的。OP的代码是完全有效的 - 无需添加任何其他内容。
附言决定将其添加为注释,因为我与OP掉在同一个坑中。
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 移除前面有空格的前2个字符串
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 在 c++ 中逐行阅读字符串,不要以空格停止
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 如何存储包含多个空格的字符串 c++
- 在特定位置为字符串添加空格
- 有没有办法在 c++ 中获取带有空格的完整字符串?
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
- 从没有空格的字符串中提取整数
- 用于拆分空格字符串的程序不起作用
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换