Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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

My purpose for doing this is because I have a loop to copy characters from certain areas of another string into a new string.

like image 286
penu Avatar asked Dec 09 '14 02:12

penu


People also ask

How do you initialize a string length?

The idea is to first, get the length L of the string is taken as input and then input the specific character C and initialize empty string str. Now, iterate a loop for L number of times. In every iteration, the specific character is concatenated with string str until the for loop ends.

How do I fix the length of a string in C++?

std::string::resize() in C++ Syntax 1: Resize the number of characters of *this to num. void string ::resize (size_type num) num: New string length, expressed in number of characters.


2 Answers

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

like image 105
EToreo Avatar answered Oct 06 '22 14:10

EToreo


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/

like image 22
spartan Avatar answered Oct 06 '22 13:10

spartan