Padding stl strings in C++

后端 未结 12 1812
一向
一向 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 22:59

    you can create a string containing N spaces by calling

    string(N, ' ');
    

    So you could do like this:

    string to_be_padded = ...;
    if (to_be_padded.size() < 10) {
      string padded(10 - to_be_padded.size(), ' ');
      padded += to_be_padded;
      return padded;
    } else { return to_be_padded; }
    

提交回复
热议问题