如何修改数组,从中删除空格,然后将其存储在新数组中

How do I modify an array, remove spaces from it, and store it in a new array?

本文关键字:数组 存储 新数组 然后 空格 何修改 删除 修改      更新时间:2023-10-16

例如,我想将此字符串的元素存储在数组中,[1 2 3; 4 5 6; 7 8 9]。

    string s = "[1 2 3;4 5 6;7 8 9]";
    string news[100];
    int leng1 = s.length();
    for (int i = 0; i < leng1; i++)
    {
        int v = test.find(";");
        if (v == -1)
        {
            limo[i] = s.substr(0, leng1);
            break;
        }
        limo[i] = s.substr(0, v);
        test = test.substr(v + 1, v + leng1);
    }
    string s = "[1 2 3;4 5 6;7 8 9]";

我想存储没有空间和半隆的数字。

如果您的目标是将这些数字存储在int数组中,则可以在不必写for循环,调用substr等的情况下完成此操作。

为此,一种方法是首先用空格替换不需要的字符。完成此操作后,就是使用C 中可用的设施的问题,该设施允许在将字符串作为输入时解析和存储项目。

以下使用std :: replace_if替换字符和std :: iStringstream来解析字符串。

#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include <algorithm>
int main()
{
    std::string s="[1 2 3;4 5 6;7 8 9]";
    // store items here
    std::vector<int> news;
    // replace unwanted characters with a space
    std::replace_if(s.begin(), s.end(), [](char ch){return ch == ']' || ch == '[' || ch == ';';}, ' ');
    // parse space delimited string into the vector
    std::istringstream strm(s);
    int data;
    while (strm >> data)
       news.push_back(data);
    // output results
    for (auto& v : news)
      std::cout << v << "n";
}

输出:

1
2
3
4
5
6
7
8
9

实时示例