Padding stl strings in C++

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

    The easiest way I can think of would be with a stringstream:

    string foo = "foo";
    stringstream ss;
    ss << setw(10) << foo;
    foo = ss.str();
    

    foo should now be padded.

    0 讨论(0)
  • 2020-12-05 23:09

    There's a nice and simple way :)

    const int required_pad = 10;
    
    std::string myString = "123";
    size_t length = myString.length();
    
    if (length < required_pad)
      myString.insert(0, required_pad - length, ' ');
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-05 23:10

    Minimal working code:

    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        for(int i = 0; i < 300; i += 11)
        {
            std::cout << std::setfill ( ' ' ) << std::setw (2) << (i % 100) << std::endl;
        }
        return 0;
    }
    
    /*
    Note:
    - for std::setfill ( ' ' ):
      - item in '' is what will be used for filling
    - std::cout may be replaced with a std::stringstream if you need it
    - modulus is used to cut the integer to an appropriate length, for strings use substring
    - std::setw is used to define the length of the needed string
    */
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-05 23:14

    You can use it like this:

    std::string s = "123";
    s.insert(s.begin(), paddedLength - s.size(), ' ');
    
    0 讨论(0)
提交回复
热议问题