Is there a way to create a string of say 256 characters at initialization with c++?
Part of my assignment requires me to "1. Create a string of 256 characters. Use repetitions of your first name."
I'm not quite sure of how to do this other than using a loop but I feel like there is an easier way.
We can fill a fixed size char array with our desired character and convert that to a string: char[] charArray = new char[N]; for (int i = 0; i < N; i++) { charArray[i] = 'a'; } String newString = new String(charArray); assertEquals(EXPECTED_STRING, newString);
To create a string from an array of characters:Type char[] title. title is a variable that can point to an array of characters. The way you tell C# that you want many characters (an array) instead of a single character is by putting square brackets after the data type (char[] instead of char).
void string ::resize (size_type num, char c ) num: is the new string length, expressed in number of characters. c: is the character needed to fill the new character space. If num > size() : character c is used to fill space. If num < size() : String is simply resized to num number of characters.
To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With