How to initialize an std::string with a length?

后端 未结 5 694
盖世英雄少女心
盖世英雄少女心 2020-12-30 02:29

If a string\'s length is determined at compile-time, how can I properly initialize it?

#include 
int length = 3;
string word[length]; //invalid         


        
相关标签:
5条回答
  • 2020-12-30 02:44

    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/

    0 讨论(0)
  • 2020-12-30 02:47

    std::string does not support lengths known at compile time. There's even a proposal for adding compile time strings to the C++ standard.

    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. 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).

    The syntax you are trying will work with static const char[]:

    static const char myString[] = "hello";
    

    Any constructor for std::string shown in the other answers is executed at runtime.

    0 讨论(0)
  • 2020-12-30 02:49

    You can initialize your string like this:

    string word = "abc"
    

    or

    string word(length,' ');
    word[0] = 'a';
    word[1] = 'b';
    word[2] = 'c';
    
    0 讨论(0)
  • 2020-12-30 03:04

    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 now equals "xxxxxxxxxx".

    0 讨论(0)
  • 2020-12-30 03:10

    You are probably looking for:

    string word(3, ' ');
    
    0 讨论(0)
提交回复
热议问题