字符串操作-分解字符串并补0

题目描述

按要求分解字符串:
输入两个数M,N
M:输入的M串字符串
N:输出的每串字符串的位数,不够补0。

eg
input:2 8  abc  123456789
out:abc00000   12345678  90000000

解题思路一

  1. C++字符串常用函数:
  • string substr (size_t pos = 0, size_t len = npos) const;
    note:第二个参数为要取的字符串长度
#include <iostream>
#include <vector>
#include <stack>
#include <string>
using namespace std;

class Solution {
public:
	vector<string> splitStr(vector<string> inStrs, int n);
};

int main()
{
	Solution sol;
	vector<string> inStrs;
	vector<string> outStrs;
	int M = 0;
	int N = 0;
	cin >> M >> N;
	for (int i = 0; i < M; i++)
	{
		string str;
		cin >> str;
		inStrs.push_back(str);
	}
	outStrs = sol.splitStr(inStrs, N);
	for (int i = 0; i < outStrs.size(); i++)
	{
		cout << outStrs[i] << "  ";
	}
	cout << endl;
	system("pause");
	return 0;
}

vector<string> Solution::splitStr(vector<string> inStrs, int n)
{
	vector<string> outStrs;
	for (int i = 0; i < inStrs.size(); i++)
	{
		string str = inStrs[i];
		int strLen = str.length();
		if (strLen <= n)//字符串长度小于n,补0
		{
 			for (int j = 0; j < (n - strLen); j++)
			{
				str += "0";
			}
			outStrs.push_back(str);
		}
		else//字符串长度大于n
		{
			int subLen = strLen;
			int beg = 0;
			int end = n;
			string strTmp;
			while (subLen >= n)//多少个n
			{
				strTmp = str.substr(beg, n);
				beg += n;
				end += n;
				outStrs.push_back(strTmp);
				subLen -= n;
			}
			if (subLen > 0)//余下的补0
			{
				strTmp = str.substr(beg, strLen);
				int addZeors = n - subLen;
				for (; addZeors > 0; addZeors--)
				{
					strTmp += "0";
				}
				outStrs.push_back(strTmp);
			}
		}
	}
	return outStrs;
}

解题思路二

  • 利用递归的思想

猜你喜欢

转载自blog.csdn.net/vict_wang/article/details/85719142
今日推荐