如何用长度初始化 std::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';

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

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

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

原文由 penu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.1k
2 个回答

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

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

s6 现在等于 “xxxxxxxxxx”

原文由 EToreo 发布,翻译遵循 CC BY-SA 3.0 许可协议

下面的呢?

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

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

原文由 spartan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏