简体   繁体   English

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

[英]How to initialize an std::string with a length?

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? ...所以我可以做这样的事情?

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

My purpose for doing this is because I have a loop to copy characters from certain areas of another string into a new 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/ 但如果必须具有指定的长度,则可以使用“填充构造函数”: http//www.cplusplus.com/reference/string/string/string/

std::string s6 (10, 'x');

s6 now equals "xxxxxxxxxx" . s6现在等于“xxxxxxxxxx”

You can initialize your string like this: 您可以像这样初始化字符串:

string word = "abc"

or 要么

string word(length,' ');
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';

您可能正在寻找:

string word(3, ' ');

std::string does not support lengths known at compile time. std::string不支持编译时已知的长度。 There's even a proposal for adding compile time strings to the C++ standard. 甚至有人建议将编译时字符串添加到C ++标准中。

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

For now you're out of luck. 现在你运气不好。 What you can do is use static const char[] which does support compile time constant strings but obviously lacks some of the niceties of std::string . 你可以做的是使用static const char[] ,它支持编译时常量字符串,但显然缺少std::string一些细节。 Whichever is appropriate depends on what you're doing. 哪个合适取决于你在做什么。 It may be that std::string features are unneeded and static char[] is the way to go or it may be that std::string is needed and the runtime cost is neglibible (very likely). 可能是std::string特性是不需要的, static char[]是要走的路,或者可能是需要std::string而且运行时成本是可忽略的(非常可能)。

The syntax you are trying will work with static const char[] : 您正在尝试的语法将使用static const char[]

static const char myString[] = "hello";

Any constructor for std::string shown in the other answers is executed at runtime. 其他答案中显示的std::string任何构造函数都在运行时执行。

How about the following? 以下怎么样?

string word;
word.resize(3);
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM