如何删除字符串中的所有空格并将数据存储在两者之间



我是一个新程序员(<1年(,所以如果我把简单的事情弄复杂,请原谅。

我正在尝试删除给定字符串中的所有空格(制表符和空格字符(,并将数据存储为向量中的单个元素。我还想考虑前导和尾随空格。

我尝试使用字符串方法在字符串中向前移动两个索引,同时检查这些字符。到目前为止,我已经重写了至少五次代码,我总是以:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void  makeTokens(string& separate);
int main()
{
    string test = "  u       65.45tt   36.12t     78.25  0.00";
    makeTokens(test);
    return 0;
}
void  makeTokens(string& separate)
{
    vector<string> tokens;
    unsigned short index1, index2 = 0;
    while (separate.at(index1) == ' ' || separate.at(index1) == 't')
    {
        index1++;
        index2 = index1 + 1;
    }
    while (index2 < separate.length())
    {
        if (separate.at(index2) == ' ' || separate.at(index2) == 't')
        {
            tokens.push_back(separate.substr(index1, index2 - index1));
            index1 = index2;
            while (separate.at(index1) == ' ' || separate.at(index1) == 't')
            {
                index1++;
            }
            index2 = index1 + 1;
        }
        else
        {
            index2++;
        }
        if (index2 == separate.length() - 1)
        {
            if (separate.at(index2) == ' ' || separate.at(index2) == 't')
            {
                tokens.push_back(separate.substr(index1));
            }
        }
    }
    for (unsigned short i = 0; i < tokens.size(); i++)
    {
        cout << tokens[i] << "|" << endl;
    }
}

我希望控制台输出:

u|
65.45|
36.12|
78.25|
0.00|

如果传递了类似的测试字符串,除了末尾有空格,我仍然想要相同的输出。

编辑:我已将索引声明更改为:

unsigned short index1 = 0;
unsigned short index2 = 0;

现在控制台输出:

u|
65.45|
36.12|
78.25|

最终的 0.00 仍然缺失。

未定义行为的第一个实例在这里:

    unsigned short index1, ...
    while (separate.at(index1) ...
//                     ^^^^^^

index1未初始化。

这很容易通过使用std::istringstream来完成:

#include <string>
#include <sstream>
#include <iostream>
#include <vector>
int main()
{
  std::string test = "  u       65.45tt   36.12t     78.25  0.00";
  std::istringstream strm(test);
  std::string word;
  std::vector<std::string> words;
  while (strm >> word)
      words.push_back(word);
  for (auto& v : words)
    std::cout << v << "|n";
}

输出:

u|
65.45|
36.12|
78.25|
0.00|

现场示例

最新更新