我需要将字符串(例如“1234567890”)转换为整数数组,但元素的宽度由用户决定。所以:
如果用户传递 1 它将是:1 2 3 4 5 6 7 8 9 0
对于 2,我将有一个数组:12 34 56 78 90
3: 1 234 567 890
4: 12 3456 7890
等等
我尝试过的:
#include <iostream>
using namespace std;
int main()
{
string textNumber;
int size;
cin >> textNumber;
cin >> size;
int length = textNumber.length();
int lenghtOfArray = length / size + (length % size ? 1 : 0);
int myArray[lenghtOfArray] = {0};
int move = lenghtOfArray- (size * lenghtOfArray - length);
int copySize = size;
int k = 0;
for(int i=0; i < length;i++) {
if(--copySize && !move){
myArray[k] += (int)textNumber[i]-48;
} else {
myArray[k] += (int)textNumber[i]-48;
++k;
copySize = size;
if(move) --move;
continue;
}
myArray[k] *= 10;
}
myArray[k] += (int)(textNumber[0]-48);
for(int i=0; i < lenghtOfArray; i++) {
cout << myArray[i] << " ";
}
}
但它并不适用于所有情况(I̶t̶̶w̶o̶r̶k̶s̶̶o̶n̶l̶y̶̶f̶o̶r̶̶s̶i̶z̶e̶=̶2̶)。
最佳答案
一种方法是使用 std::stoi
连同 substr
std::string
的成员函数将字符串分成几部分并解析结果:
cin >> s;
cin >> size;
int len = s.length();
int count = (len+size-1) / size;
vector<int> res(count);
int pos = count-1;
while (s.length() > size) {
res[pos--] = stoi(s.substr(s.length()-size));
s = s.substr(0, s.length()-size);
}
if (s.length()) {
res[0] = stoi(s);
}
注意需要使用std::vector<int>
而不是数组,因为 C++ 标准不允许可变长度数组(g++ 将其作为流行的扩展提供)。
关于c++ - 如何将字符串转换为具有确定宽度的整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407453/