在 C++ 中填充 stl 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/667183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:35:53  来源:igfitidea点击:

Padding stl strings in C++

c++stringpaddingstdstring

提问by Alex B

I'm using std::stringand need to left pad them to a given width. What is the recommended way to do this in C++?

我正在使用std::string并且需要将它们左填充到给定的宽度。在 C++ 中推荐的方法是什么?

Sample input:

样本输入:

123

pad to 10 characters.

填充到 10 个字符。

Sample output:

示例输出:

       123

(7 spaces in front of 123)

(123前7位)

回答by bayda

std::setw (setwidth) manipulator

std::setw (setwidth) 操纵器

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

or

或者

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

outputs padded 77 and "hi!".

输出填充 77 和“嗨!”。

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

如果您需要结果作为字符串,请使用 std::stringstream 的实例而不是 std::cout 对象。

ps: responsible header file <iomanip>

ps:负责的头文件 <iomanip>

回答by Brian R. Bondy

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;
}

回答by Naveen

You can use it like this:

你可以这样使用它:

std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');

回答by greyfade

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

我能想到的最简单的方法是使用字符串流:

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

fooshould now be padded.

foo现在应该被填充。

回答by Antti Huima

you can create a string containing N spaces by calling

您可以通过调用创建一个包含 N 个空格的字符串

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; }

回答by Francois Nedelec

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;
}

回答by Andrew Grant

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, ' ');

回答by Andy Mikula

How about:

怎么样:

string s = "          "; // 10 spaces
string n = "123";
n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;

回答by vincent thorpe

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

我正在寻找这个话题,因为我正在开发 VCL;无论如何,制作一个函数并不是那么难。

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.

在这两种情况下,它都会在右侧添加 10 个空格。我建议使用等宽字体,如 courier 或 consolas 以获得正确的格式。

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

当您不使用等宽字体时会发生这种情况
johnny____
cash______

// using monospace font the output will be
johnny____
cash______

Both cases have the same length.

两种情况具有相同的长度。

回答by Aleksandr

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
*/