如何用长度初始化std :: string?

pen*_*enu 8 c++ string

如果在编译时确定字符串的长度,我该如何正确初始化它?

#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';
Run Code Online (Sandbox Code Playgroud)

...所以我可以做这样的事情?

示例:http://ideone.com/FlniGm

我这样做的目的是因为我有一个循环将字符从另一个字符串的某些区域复制到一个新字符串.

ETo*_*reo 17

字符串是可变的,它的长度可以在运行时更改.但如果必须具有指定的长度,则可以使用"填充构造函数":http: //www.cplusplus.com/reference/string/string/string/

std::string s6 (10, 'x');
Run Code Online (Sandbox Code Playgroud)

s6现在等于"xxxxxxxxxx".


zac*_*yee 7

您可以像这样初始化字符串:

string word = "abc"
Run Code Online (Sandbox Code Playgroud)

或者

string word(length,' ');
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
Run Code Online (Sandbox Code Playgroud)


小智 6

下面的怎么样?

string word;
word.resize(3);
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
Run Code Online (Sandbox Code Playgroud)

有关调整字符串大小的更多信息:http://www.cplusplus.com/reference/string/string/resize/


Pra*_*tic 5

std::string不支持编译时已知的长度。甚至有人提议将编译时字符串添加到 C++ 标准中。

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4121.pdf

现在你运气不好。您可以做的是使用static const char[]它确实支持编译时常量字符串,但显然缺乏std::string. 哪个合适取决于您在做什么。可能某些std::string功能是不需要的,但这static char[]是可行的方法,也可能是std::string需要的功能,但运行时成本可以忽略不计(很可能)。

您正在尝试的语法将适用static const char[]

static const char myString[] = "hello";
Run Code Online (Sandbox Code Playgroud)

其他答案中显示的任何构造函数std::string都在运行时执行。