Padding stl strings in C++

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

    void padTo(std::string &str, const size_t num, const char paddingChar = ' ')
    {
        if(num > str.size())
            str.insert(0, num - str.size(), paddingChar);
    }
    
    int main(int argc, char **argv)
    {
        std::string str = "abcd";
        padTo(str, 10);
        return 0;
    }
    

提交回复
热议问题