Create string with specified number of characters Create string with specified number of characters c c

Create string with specified number of characters


Taking a look at the constructor reference of basic_string, one can see that there is no easy way of repeating a complete string. For a single character, you could use (2) like this:

std::string s(5, 'a'); // s == "aaaaa"

For generating a string repetition, you'll need some workaround. It's easier to do this post-construction by simply filling the string with, for example, std::generate (having fun with algorithms).

#include <string>#include <algorithm>// ...std::string pattern("Xeo ");auto pattern_it = pattern.begin();std::string s(256, '\0');std::generate(s.begin(), s.end(),    [&]() -> char {       if(pattern_it == pattern.end())        pattern_it = pattern.begin();      return *pattern_it++; // return current value and increment    });

Live example.


If you want a very long string, you can cut down the number of loop repetitions by doubling.

#include <string>using std::string;string repeatToLength ( unsigned len, string s ) {  string r, si = s;  // add all the whole multiples of s.  for ( unsigned q = len / s.size(); q > 0; q >>= 1 ) {    if ( q & 1 ) r += si; // add si to r if the low bit of q is 1    si +=  si; // double si  }  r += s.substr ( 0, len - r.size() ); // add any remainder  return r;}


const string myName = "Blivit";int numLeftOver = 256 % myName.length();string Names;for ( int Index = 0; Index < (256 / myName.length() ); ++Index ) {   Names += myName;}Names += myName.substr(0, numLeftOver); 

This is if you want to generate the string. I'm fairly sure there is a shorter way to do this...