如何修改数组,从中删除空格,然后将其存储在新数组中
How do I modify an array, remove spaces from it, and store it in a new array?
例如,我想将此字符串的元素存储在数组中,[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
实时示例
相关文章:
- 多维数组存储三种不同的数据类型?
- C++将原始字符数组存储在元组中
- 将十六进制字符数组存储在字节数组中,而无需更改为 ASCII 或其他任何东西
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 如何将JSON数组存储在Arduino程序中
- 如何在AVR(例如:ATMega)或Arduino微控制器上制作2D PROGMEM阵列的1D PROGMEM数组(存储
- 使用 char 数组存储数据
- 使用平面数组存储的元组容器
- 数组 存储并要求用户搜索它
- 将值从一个 char 数组存储到另一个 char 数组
- 如何使字符串数组存储在向量中
- 将构造的静态数组存储在多个文件中的内存中
- 将整数数组存储在堆上并通过指针访问它们
- c++声明一个数据类型的字节数组,该数组存储在字符串中
- 使用指针数组存储阶乘计算的所有中间结果
- 使用异构数组存储不同的子类
- 读取文件内容,存储在数组中,向数组添加更多内容,然后将新数组存储在文件C++中
- 尝试将复杂数组存储到类 c++ 中
- 在字节数组存储中嵌入 int/string