2016华为机试题:字符串按指定长度分割

问题描述:

输入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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值