我有一个字符串"Bla bla *.h *.cpp *.png"
。现在我想将所有文件名放在向量中。所以我的载体将有
vec[0] = "*.h";
vec[1] = "*.cpp";
vec[2] = "*.png";
以下是我写的内容。
void FileMgr::parseCmdLineForTextSearch(std::string b)
{
for (int i = 0; i < b.length(); i++)
{
std::size_t pos = b.find(" *.");
std::cout << "pos:" << pos << "\n";
std::size_t pos_ = b.find(pos, " "); // this line does not
// work, but I want to somehow get the position where
// the blank space again started so that I can get the
// the substring from **pos** to just before that blank space
//thus giving me the exact end point of *.cpp or *.h
std::string str2 = b.substr(pos, pos_);
//^^ this pos_ will help //
//me to get the required substring i.e, *.cpp or *.h
patternVector.push_back(str);
}
}
P.S:可能还有其他更好的方法来实现它。但我不知何故想按照我上面提到的方式去做。此外,我需要确保即使我找到空白的终点,它应该始终在整个文本之后。我不想最终找到文本bla bla
之间的空白区域。是否可能?
答案 0 :(得分:1)
你的循环没有任何意义。对b
中的每个字符执行一次逻辑,但逻辑本身不依赖于i
。因此无论你的循环体是什么,只需将相同的字符串b.length()
添加到patternVector
。
你要做的是利用你对b
的了解:它是一堆空格分隔的单词,其中一些单词以"*."
开头。所以让我们这样做:
void FileMgr::parseCmdLineForTextSearch(const std::string& b)
// don't need a copy ^^^^^^^^^^^^^^^^^^
{
std::istringstream iss(b);
std::string word;
while (iss >> word) { // for each word in b
if (word.find("*.") == 0) { // if it starts with *.
patternVector.push_back(word); // add it
}
}
}