Multiplying a string by an int in C++

Viewed 73066

What do I have to do so that when I

string s = ".";

If I do

cout << s * 2;

Will it be the same as

cout << "..";

?

9 Answers

I used operator overloading to simulate this behavior in c++.

#include <iostream>
#include <string>
using namespace std;

/* Overloading * operator */
string operator * (string a, unsigned int b) {
    string output = "";
    while (b--) {
        output += a;
    }
    return output;
}


int main() {
    string str = "abc";
    cout << (str * 2);
    return 0;
}

Output: abcabc

You can do this:

#include <iostream>
using namespace std;

int main()
{
    string text, new_text;
    int multiply_number;

    cin >> text >> multiply_number;

    /*
        First time in the 'for' loop:  new_text = new_text + text
                                       new_text = "" + "your text"
                                       new_text = "your text"

        Second time in the 'for' loop: new_text = new_text + text
                                       new_text = "your text" + "your text"
                                       new_text = "your textyour text"...n times
    */

    for(int i=0; i<multiply_number; i++)
    {
        new_text += text;
    }

    cout << new_text << endl;    // endl="\n"

    system("pause");
    return 0;
}

In Python you can multiply string like this:

text = "(Your text)"
print(text*200)
std::string StrMultiply(const char* str, size_t count) {
        size_t stringsize = strlen(str);
        size_t buffersize = stringsize * count + 1;
        string res(buffersize,'\0');
        char* end = res._Unchecked_end();
        char* offset = res._Unchecked_begin();
        for (size_t i = 0;i < count; offset += stringsize,i++)
        {
            memcpy(offset, str, stringsize);
        }
        // mark the end
        res[buffersize - 1] = '\0';
        return res;
    }
        inline std::string operator*(std::string left, size_t right) {
            return StrMultiply(left.c_str(), right);
        }

here is a ram-friendly solution, 10 times faster than using stringstreams or string::append

Like JRG did, but in a single line

std::cout << std::string(70,'-') << std::endl;

This will create a string, filled with - (dashes), 70 characters long, and breaking the line at the end with std::endl;

Related