Multiplying a string by an int in c++

2019-01-27 12:08发布

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

?

5条回答
Evening l夕情丶
2楼-- · 2019-01-27 12:35

They can't be multipled but I think you can write your own function to do this, something like -

#include <iostream>
#include <string>

std::string operator*(std::string s, size_t count)
{
    std::string ret;
    for(size_t i = 0; i < count; ++i)
    {
        ret = ret + s;
    }
    return ret;
}


int main()
{
    std::string data = "+";
    std::cout << data * 10 << "\n";
}

It's probably not the best idea though, it will be very confusing to anyone looking at the code and not expecting this,

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-27 12:36

No, std::string has no operator *. You can add (char, string) to other string. Look at this http://en.cppreference.com/w/cpp/string/basic_string

And if you want this behaviour (no advice this) you can use something like this

#include <iostream>
#include <string>

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(const std::basic_string<Char, Traits, Allocator> s, size_t n)
{
   std::basic_string<Char, Traits, Allocator> tmp = s;
   for (size_t i = 0; i < n; ++i)
   {
      tmp += s;
   }
   return tmp;
}

template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(size_t n, const std::basic_string<Char, Traits, Allocator>& s)
{
   return s * n;
}

int main()
{
   std::string s = "a";
   std::cout << s * 5 << std::endl;
   std::cout << 5 * s << std::endl;
   std::wstring ws = L"a";
   std::wcout << ws * 5 << std::endl;
   std::wcout << 5 * ws << std::endl;
}

http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313

查看更多
趁早两清
4楼-- · 2019-01-27 12:36

There is no predefined * operator that will multiply a string by an int, but you can define your own:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string operator*(const string& s, unsigned int n) {
    stringstream out;
    while (n--)
        out << s;
    return out.str();
}

string operator*(unsigned int n, const string& s) { return s * n; }

int main(int, char **) {
    string s = ".";
    cout << s * 3 << endl;
    cout << 3 * s << endl;
}
查看更多
ら.Afraid
5楼-- · 2019-01-27 12:43

std::string has a constructor of the form

std::string(size_type count, char c);

that will repeat the character. For example

#include <iostream>

int main() {
   std::string stuff(2, '.');
   std::cout << stuff << std::endl;
   return 0;
}

will output

..
查看更多
贼婆χ
6楼-- · 2019-01-27 12:45

Strings cannot be multiplied.

if s is a char

'.'     //this has 46 ascii-code

then

cout << (char)((int)s * 2);

will give you

'/'     //this has 92 ascii-code
查看更多
登录 后发表回答