如何初始化带有长度的std :: string? [英] How to initialize an std::string with a length?
本文介绍了如何初始化带有长度的std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果字符串的长度是在编译时确定的,我该如何正确初始化它?
If a string's length is determined at compile-time, how can I properly initialize it?
#include <string>
int length = 3;
string word[length]; //invalid syntax, but doing `string word = " "` will work
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
...以便我可以做这样的事情?
...so that i can do something like this?
我这样做的目的是因为我有一个循环,可以将字符从另一个字符串的某些区域复制到新字符串中。
My purpose for doing this is because I have a loop to copy characters from certain areas of another string into a new string.
推荐答案
字符串是可变的,并且其长度可以在运行时更改。但是,如果必须具有指定的长度,则可以使用填充构造函数:
http://www.cplusplus.com/reference/string/string/string/
A string is mutable and it's length can changed at run-time. But you can use the "fill constructor" if you must have a specified length: http://www.cplusplus.com/reference/string/string/string/
std::string s6 (10, 'x');
s6
现在等于 xxxxxxxxxx 。
这篇关于如何初始化带有长度的std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文