Padding stl strings in C++

2019-01-14 20:17发布

I'm using std::string and need to left pad them to a given width. What is the recommended way to do this in C++?

Sample input:

123

pad to 10 characters.

Sample output:

       123

(7 spaces in front of 123)

9条回答
Bombasti
2楼-- · 2019-01-14 20:37

Create a new string of 10 spaces, and work backwards in both string.

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;
}
查看更多
Animai°情兽
3楼-- · 2019-01-14 20:45

There's a nice and simple way :)

const int required_pad = 10;

std::string myString = "123";
size_t length = myString.length();

if (length < required_pad)
  myString.insert(0, required_pad - length, ' ');
查看更多
女痞
4楼-- · 2019-01-14 20:49

The easiest way I can think of would be with a stringstream:

string foo = "foo";
stringstream ss;
ss << setw(10) << foo;
foo = ss.str();

foo should now be padded.

查看更多
登录 后发表回答