Ser*_*i G 31 c++ string token delimiter
我有一些文字(有意义的文字或算术表达),我想把它分成文字.
如果我有一个分隔符,我会使用:
std::stringstream stringStream(inputString);
std::string word;
while(std::getline(stringStream, word, delimiter))
{
wordVector.push_back(word);
}
Run Code Online (Sandbox Code Playgroud)
如何将字符串分成具有多个分隔符的标记?
Soa*_*Box 43
假设其中一个分隔符是换行符,则以下内容读取该行并进一步按分隔符对其进行拆分.在这个例子中,我选择了分隔符空格,撇号和分号.
std::stringstream stringStream(inputString);
std::string line;
while(std::getline(stringStream, line))
{
std::size_t prev = 0, pos;
while ((pos = line.find_first_of(" ';", prev)) != std::string::npos)
{
if (pos > prev)
wordVector.push_back(line.substr(prev, pos-prev));
prev = pos+1;
}
if (prev < line.length())
wordVector.push_back(line.substr(prev, std::string::npos));
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*ith 18
如果你有提升,你可以使用:
#include <boost/algorithm/string.hpp>
std::string inputString("One!Two,Three:Four");
std::string delimiters("|,:");
std::vector<std::string> parts;
boost::split(parts, inputString, boost::is_any_of(delimiters));
Run Code Online (Sandbox Code Playgroud)
dar*_*une 10
std::regex
Astd::regex
可以在几行中进行字符串拆分:
std::regex re("[\\|,:]");
std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last;//the '-1' is what makes the regex split (-1 := what was not matched)
std::vector<std::string> tokens{first, last};
Run Code Online (Sandbox Code Playgroud)
我不知道为什么没有人指出手动方式,但这里是:
const std::string delims(";,:. \n\t");
inline bool isDelim(char c) {
for (int i = 0; i < delims.size(); ++i)
if (delims[i] == c)
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
并在功能上:
std::stringstream stringStream(inputString);
std::string word; char c;
while (stringStream) {
word.clear();
// Read word
while (!isDelim((c = stringStream.get())))
word.push_back(c);
if (c != EOF)
stringStream.unget();
wordVector.push_back(word);
// Read delims
while (isDelim((c = stringStream.get())));
if (c != EOF)
stringStream.unget();
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以根据需要对 delims 做一些有用的事情。
归档时间: |
|
查看次数: |
50342 次 |
最近记录: |