Padding stl strings in C++

后端 未结 12 1850
一向
一向 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

    std::string pad_right(std::string const& str, size_t s)
    {
        if ( str.size() < s )
            return str + std::string(s-str.size(), ' ');
        else
            return str;
    }
    
    std::string pad_left(std::string const& str, size_t s)
    {
        if ( str.size() < s )
            return std::string(s-str.size(), ' ') + str;
        else
            return str;
    }
    

提交回复
热议问题