如何构造具有可变数量空格的std :: string?

Mic*_*eth 7 c++

如果我有以下代码:

std::string name =   "Michael";
std::string spaces = "       ";
Run Code Online (Sandbox Code Playgroud)

我将如何以编程方式创建spaces字符串(包含所有空格的字符串,长度与name变量匹配)?

mea*_*gar 13

您可以将字符和长度传递给字符串,它将使用给定字符填充该长度的字符串:

std::string spaces(7, ' ');
Run Code Online (Sandbox Code Playgroud)

您可以使用.size()std :: string 的属性来查找名称的长度; 结合以上内容:

std::string name = "Michael";
std::string spaces(name.size(), ' ');
Run Code Online (Sandbox Code Playgroud)


Syl*_*Syl 9

来自http://www.cplusplus.com/reference/string/string/string/

std::string spaces(name.length(), ' ');
Run Code Online (Sandbox Code Playgroud)

  • 注意:我会使用`size()`而不是`length()`因为`size()`匹配STL容器(会使你的代码更加一致).虽然+1. (2认同)

Sim*_*ter 6

std::string spaces(name.size(), ' ');
Run Code Online (Sandbox Code Playgroud)