Padding stl strings in C++

2019-01-14 20:17发布

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

pad to 10 characters.

Sample output:

       123

(7 spaces in front of 123)

9条回答
虎瘦雄心在
2楼-- · 2019-01-14 20:25

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>

查看更多
Deceive 欺骗
3楼-- · 2019-01-14 20:25
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;
}
查看更多
Juvenile、少年°
4楼-- · 2019-01-14 20:33

You can use it like this:

std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');
查看更多
爷、活的狠高调
5楼-- · 2019-01-14 20:36
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;
}
查看更多
Summer. ? 凉城
6楼-- · 2019-01-14 20:36

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; }
查看更多
混吃等死
7楼-- · 2019-01-14 20:37

How about:

string s = "          "; // 10 spaces
string n = "123";
n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;
查看更多
登录 后发表回答