问题描述:
输入M个字符串,按指定长度N拆分每个字符串,输出新的字符串,长度不是N的整数倍的字符串请在后面补数字0
输入:输入整数M,N,以逗号隔开
每行一个字符串,共M个字符串,每行字符串小于50个字符
输出:按指定长度N拆分字符串,输出拆分后的字符串
示例:
输入:
2,8
abc
123456789
输出:
abc00000
12345678
90000000
下面程序是在VS2013中调试的,分别用C和C++的STL两种方法实现:
<span style="font-size:14px;">// 字符串按指定长度分割.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<cstdlib>
#define useC 1
#if useC
#include <string.h>
#include <stdio.h>
#else
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
#endif
int _tmain(int argc, _TCHAR* argv[])
{
#if useC
int M, N;
while (scanf("%d,%d",&M,&N) && M && N)
{
char s1[100][100] = {"0"};
//printf("%s",s1[0]);
for (int i = 0; i < M; i++)
{
scanf("%s", s1[i]);
}
for (int i = 0; i < M; i++)
{
int temp = strlen(s1[i]);
if (temp % N != 0)
{
for (int j = temp; j < (temp / N + 1)*N; j++)
{
*(s1[i]+j) = '0';
}
}
for (int j = 0; j < (strlen(s1[i])) && *(s1[i] + j); j++)
{
printf("%c", *(s1[i] + j));
if ((j + 1) % N == 0) printf("\n");
}
}
}
#else
int M, N; char c;
vector<string> svec;
while (cin >> M >> c >> N && M && N)
{
for (int i = 0; i < M; i++)
{
string temps;
cin >> temps;
int tempi = temps.size();
for (int j = 1; j <= tempi / N; j++)
{
temps.insert(j*N + (j-1),"\n");//随着插入字符串,字符串长度变化了,原来插入的位置变了
}
tempi = temps.size();
//cout << tempi << endl;
for (int j = tempi; j < (tempi / (N+1)+1)*(N+1)-1; j++)
{
temps.insert(j , "0");
}
temps.insert((tempi / (N + 1) + 1)*(N + 1)-1, "\n");
svec.push_back(temps);
}
for (vector<string>::iterator it = svec.begin();it!=svec.end(); it++)
{
cout<<*it;
}
//向量清空
svec.clear();
}
#endif
system("pause");
return 0;
}
</span>
<span style="font-size:14px;">
</span>