习题5-1代码对齐

UVa1593 Alignment of Code
【题目描述】
在这里插入图片描述
【分析】
很简单,用 vector 记录所有的输入,取每一行每个元素的最大长度 max_len[i] ,下面与之对应的单词不足的长度用空格代替,他们之间也就是差了 max_len[i]-str[i][j].length()+1 个空格。
其中使用stringstream来根据空格划分字符串。

【代码】

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<sstream>
#include<vector>
using namespace std;
const int maxn = 1000 + 10;
int main()
{
	int n, max_len[maxn], sum = 0;
	cin >> n;
	getchar();
	vector<string> vect[maxn];	//用来记录每行每列的单词
	memset(max_len, 0, sizeof(max_len));
	while (n--)
	{
		int cnt = 0;
		string str, buf;
		getline(cin, str);
		stringstream ss(str);
		while (ss >> buf)
		{
			vect[sum].push_back(buf);
			if (max_len[cnt] < buf.length()) 	//得到每列单词的最大长度
				max_len[cnt] = buf.length();
			cnt++;
		}
		sum++;
	}
	for (int i = 0;i < sum;i++)
	{
		for (int j=0;j<vect[i].size();j++)
		{
			cout << vect[i][j];
			int len = vect[i][j].length();
			for (int k = 1;k <= max_len[j] - len + 1;k++) cout << " "; //差的字符数用空格来代替
		}
		cout << endl;
	}
	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值