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;
}