【问题标题】:How to initialize an std::string with a length?如何用长度初始化 std::string?
【发布时间】:2014-12-09 02:22:37
【问题描述】:

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

#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

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

【问题讨论】:

  • 你的意思是在编译时?如果它在运行时,只需将一些字母填入其中,std::string 将找出其余的。如果你的意思是编译时间,那么不,std::string 不支持这个。
  • 是的,抱歉我的意思是编译时间

标签: c++ string


【解决方案1】:

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

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

s6 现在等于 "xxxxxxxxxx"

【讨论】:

    【解决方案2】:

    下面的呢?

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

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

    【讨论】:

      【解决方案3】:

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

      string word = "abc"
      

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

      【讨论】:

      • 如果要复制的字符串在编译时才知道,这将不起作用。
      • @penu 你为什么要使用a[0] = 'h'; a[1] = 'i'; 而不是更自然的a = "hi";
      • @greatwolf 我有一个 for 循环可以从另一个字符串的某些区域复制字符
      • @penu 好的,然后就做a += other_str;。您现在访问a[i] 的方式是错误的,因为不能保证std::string 已分配给您尝试访问的索引。 IOW assert(i &lt; a.length());.
      • @penu 很抱歉造成误解。如果你想像这样逐个字符地初始化它,你必须分配正确数量的索引。
      【解决方案4】:

      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";
      

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

      【讨论】:

        【解决方案5】:

        您可能正在寻找:

        string word(3, ' ');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-12
          • 2016-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多