
使用多个分隔符分割字符串
在将文本分割成有意义的单元时,开发人员经常遇到将字符串分成单词的需要。虽然传统方法足以满足单个分隔符,但当涉及多个分隔符时,有哪些选项可用?
为了解决这一挑战,可以实现采用多个分隔符进行字符串分割的技术。让我们深入研究解决方案。
在 C 中,使用字符串流解析具有单个分隔符的字符串的语法如下:
1 2 3 4 5 6 | std::stringstream stringStream(inputString);
std::string word;
while (std::getline(stringStream, word, delimiter))
{
wordVector.push_back(word);
}
|
登录后复制
为了容纳多个分隔符,我们首先阅读整行放入缓冲区。随后,我们遍历该行,识别任何指定分隔符出现的位置。通过当前分隔符位置减去前一个位置,我们得到代表单词的子字符串,并将其添加到词向量中。
例如,如果我们选择空格、撇号和分号作为分隔符,则以下代码完成任务:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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));
}
|
登录后复制
以上是如何在 C 中使用多个分隔符拆分字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!