Talk is cheap, show me the code.
一、问题描述
连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组
输入例子:
abc
123456789
输出例子:
abc00000
12345678
90000000
二、问题分析
要求输入两次,但其实对于两次的处理步骤完全一致,可以再细化成一次一次输入处理。要求输出到长度为8的新字符串数组,这里可以考虑两种方式,保存这个数组,或者不保存直接输出这个数组。下面分别介绍这两种实现方式:
解决方式1:
保存每个长度为8的字符串数组:
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
int main()
{
string s1;
while (cin >> s1)
{
vector<string> vect;
int m = s1.size() / 8;
for (int i = 0; i < m; i++)
{
vect.push_back(s1.substr(i*8, 8));
}
if ((s1.size() % 8) != 0)
{
int t = 8 - s1.size()%8;
for (int i = 0; i < t; i++)
{
s1 += '0';
}
vect.push_back(s1.substr(m * 8));
}
for (vector<string>::iterator it = vect.begin(); it != vect.end(); ++it)
{
cout << *it << endl;
}
}
return 0;
}
时间复杂度和空间复杂度都和字符串的长度有关。
解决方式2:
不保存处理后的字符串数组,直接输出:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
while (s.size() > 8)
{
cout << s.substr(0, 8) << endl;
s = s.substr(8);
}
int m = s.size();
for (int i = 0; i < 8 - m; i++)
{
s += "0";
}
cout << s << endl;
}
return 0;
}
时间复杂度和字符串长度有关,但空间复杂度为常量。