Padding stl strings in C++

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

    I was looking the topic because Im developing VCL; Anyway making a function wasn't not so hard.

    void addWhiteSpcs(string &str, int maxLength) {
        int i, length;
    
        length = str.length();
        for(i=length; i<maxLength; i++)
        str += " ";
    };
    
    string name1 = "johnny";
    string name2 = "cash";
    
    addWhiteSpcs(name1, 10);
    addWhiteSpcs(name2, 10);
    

    In both cases it will add to the right 10 blank spaces. I Recomend to use monospace fonts like courier or consolas for a correct format.

    This is what happens when you're not using monospace font
    johnny____
    cash______

    // using monospace font the output will be
    johnny____
    cash______
    

    Both cases have the same length.

    0 讨论(0)
  • 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; }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-05 23:03

    std::setw (setwidth) manipulator

    std::cout << std::setw (10) << 77 << std::endl;
    

    or

    std::cout << std::setw (10) << "hi!" << std::endl;
    

    outputs padded 77 and "hi!".

    if you need result as string use instance of std::stringstream instead std::cout object.

    ps: responsible header file <iomanip>

    0 讨论(0)
  • 2020-12-05 23:06
    string t = string(10, ' ') + to_string(123);
    cout << t.substr(t.size() - 10) << endl;
    

    Try it online!

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

    Create a new string of 10 spaces, and work backwards in both string.

    string padstring(const string &source, size_t totalLength, char padChar)
    {
        if (source.length() >= totalLength) 
            return source;
    
        string padded(totalLength, padChar);
        string::const_reverse_iterator iSource = source.rbegin();
        string::reverse_iterator iPadded = padded.rbegin();
        for (;iSource != source.rend(); ++iSource, ++iPadded)
            *iPadded = *iSource;
        return padded;
    }
    
    0 讨论(0)
提交回复
热议问题