我正在使用 std::string
,需要将它们左侧填充到给定的宽度。在 C++ 中推荐使用什么方法来完成这个任务?
示例输入:
123
填充至10个字符。
示例输出:
123
(123 前有 7 个空格)
我在查找这个主题,因为我正在开发VCL;无论如何,制作一个函数并不是那么困难。
void addWhiteSpcs(string &str, int maxLength) {
int i, length;
length = str.length();
for(i=length; i<maxLength; i++)
str += " ";
};
string name1 = "johnny";
string name2 = "cash";
addWhiteSpcs(name1, 10);
addWhiteSpcs(name2, 10);
// using monospace font the output will be
johnny____
cash______
这两种情况长度相同。
std::size_t pad_size = 10, value = 123;
std::string t = std::string(pad_size , ' ') + std::to_string(value);
std::string padded = t.substr(std::min(t.size() - pad_size, pad_size));
const int column_len = 50;
string s;
s = "....some value ... ";
int fill_pad = column_len - s.length();
std::cout << s << std::setw(fill_pad) << " Second column " << other_field << std::endl;
string padstring(const string &source, size_t totalLength, char padChar)
{
if (source.length() >= totalLength)
return source;
string padded(totalLength, padChar);
string::const_reverse_iterator iSource = source.rbegin();
string::reverse_iterator iPadded = padded.rbegin();
for (;iSource != source.rend(); ++iSource, ++iPadded)
*iPadded = *iSource;
return padded;
}