在C++中填充stl字符串

76

我正在使用 std::string,需要将它们左侧填充到给定的宽度。在 C++ 中推荐使用什么方法来完成这个任务?

示例输入:

123

填充至10个字符。

示例输出:

       123

(123 前有 7 个空格)

14个回答

0

我在查找这个主题,因为我正在开发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);

在这两种情况下,它都会向右添加10个空格。我建议使用等宽字体,如Courier或Consolas,以获得正确的格式。
这就是当您不使用等宽字体时会发生的情况: johnny____ cash______
// using monospace font the output will be
johnny____
cash______

这两种情况长度相同。


0
如果您想在不使用流的情况下进行填充:
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));

在线试用!


-1
这个怎么样?
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;

-3
创建一个包含10个空格的新字符串,并在两个字符串中向后工作。
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接