Padding stl strings in C++

后端 未结 12 1824
一向
一向 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:13

    How about:

    string s = "          "; // 10 spaces
    string n = "123";
    n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;
    

提交回复
热议问题