Padding stl strings in C++

后端 未结 12 1849
一向
一向 2020-12-05 22:15

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
         


        
12条回答
  •  臣服心动
    2020-12-05 23:06

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

提交回复
热议问题