如何在C+中不使用stringstream和strtok拆分字符串(提取单词)+;? < C++ > 如何分割一个字符串(提取单词),没有 String Strue和 Strtok < /Cord>

如何在C+中不使用stringstream和strtok拆分字符串(提取单词)+;? < C++ > 如何分割一个字符串(提取单词),没有 String Strue和 Strtok < /Cord>,c++,c++11,c++14,C++,C++11,C++14,我想拆分一个字符串,该字符串在每个单词之间有多个连续空格,并且它可能跨越多行,在新行开始之前也可能有空白 到目前为止,我有这个,但它只能处理一个空间 while (input.compare(word) != 0) { index = input.find_first_of(" "); word = input.substr(0,index); names.push_back(word); input = input.substr(index+1, input.lengt

我想拆分一个字符串,该字符串在每个单词之间有多个连续空格,并且它可能跨越多行,在新行开始之前也可能有空白

到目前为止,我有这个,但它只能处理一个空间

while (input.compare(word) != 0)
{
   index = input.find_first_of(" ");
   word = input.substr(0,index);
   names.push_back(word);
   input = input.substr(index+1, input.length());
}
谢谢

这里有一个参考:

std::string input = "   hello   world   hello    "; // multiple spaces
std::string word = "";
std::vector<std::string> names;

while (input.compare(word) != 0)
{
   auto index = input.find_first_of(" ");
   word = input.substr(0,index);

   input = input.substr(index+1, input.length());

   if (word.length() == 0) {
      // skip space
      continue;
   }

   // Add non-space word to vector
   names.push_back(word);
}
std::string input=“hello world hello”//多空间
std::string word=“”;
std::矢量名称;
while(输入。比较(word)!=0)
{
自动索引=输入。首先查找(“”)中的\u;
word=输入。substr(0,索引);
input=input.substr(索引+1,input.length());
if(word.length()==0){
//跳过空格
继续;
}
//将非空格字添加到向量
姓名。推回(单词);
}

检查C++中如何不使用String Strand和Strtok的字符串(提取单词)的复制(使用代码< > Boo::算法::分割< /C>)。另外,您为什么不想使用

stringstream
?对于类似的示例,如果word为空,请不要推回。请参阅“拆分字符串并在不使用mem alloc的情况下处理每个零件”中的示例。只需使用split_se()而不是split()@codekaizer谢谢你的链接,但是那里的所有代码都使用我不想要的库。嗨@Yakk,同意使用
substr
。是否有一种优雅的方法来防止复制?使用字符串视图(C++17)或编写自己的。使用
=
首先查找
substr
并转换为std::string;所以没那么难。为什么不使用
find_first_not_of
跳过定界符,然后使用
find_first_of
找到定界符,在这两者之间你有你的toke.@JobNick,以便OP轻松区分缺少的内容。