C++ str_pad



#include <iostream>
#include <string>
 
using namespace std;
enum STR_PAD {STR_PAD_RIGHT, STR_PAD_LEFT, STR_PAD_BOTH};
 
string str_pad(const string &str, int pad_length, string pad_string=" ", STR_PAD pad_type=STR_PAD_RIGHT)
{
    int i,j,x;
    int str_size = str.size();
    int pad_size = pad_string.size();
    if (pad_length<=str_size || pad_size<1)
        return str;
 
    string o;
    o.reserve(pad_length);//allocate enough memory only once
 
    if (pad_type==STR_PAD_RIGHT)
    {
        for(i=0,x=str_size; i<x; i++)
            o.push_back( str[i] );
        for(i=str_size; i<pad_length; )
            for(j=0; j<pad_size && i<pad_length; j++,i++)
                o.push_back( pad_string[j] );
    }
    else if (pad_type==STR_PAD_LEFT)
    {
        int a1= pad_length-str_size;
        for(i=0; i<a1; )
            for(j=0; j<pad_size && i<a1; j++,i++)
                o.push_back( pad_string[j] );
        for(i=0,x=str_size; i<x; i++)
            o.push_back( str[i] );
    }
    else if (pad_type==STR_PAD_BOTH)
    {
        int a1= (pad_length-str_size)/2;
        int a2= pad_length-str_size-a1;
        for(i=0; i<a1; )
            for(j=0; j<pad_size && i<a1; j++,i++)
                o.push_back( pad_string[j] );
        for(i=0,x=str_size; i<x; i++)
            o.push_back( str[i] );
        for(i=0; i<a2; )
            for(j=0; j<pad_size && i<a2; j++,i++)
                o.push_back( pad_string[j] );
    }
    return o;
}
 
int main(int argc, char *argv[])
{
 
    cout <<"|"<< str_pad("john",20)                   <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"-")               <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"-",STR_PAD_LEFT)  <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"-",STR_PAD_RIGHT) <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"-",STR_PAD_BOTH)  <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"=-",STR_PAD_LEFT) <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"=-",STR_PAD_RIGHT)<<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"=-",STR_PAD_BOTH) <<"|"<< endl;
    cout <<"|"<< str_pad("john",0,"-")                <<"|"<< endl;
    cout <<"|"<< str_pad("john",-10," ")              <<"|"<< endl;
    cout <<"|"<< str_pad("john",20,"")                <<"|"<< endl;
 
    return 0;
}
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)