【问题标题】:Multiplying a string by an int in C++在 C++ 中将字符串乘以 int
【发布时间】:2012-08-04 07:21:00
【问题描述】:

当我这样做时,我该怎么做

string s = ".";

如果我这样做

cout << s * 2;

会不会一样

cout << "..";

?

【问题讨论】:

  • 它甚至不会编译
  • 你自己试试看吧?
  • 如果你问如何使它工作更好
  • 尽管答案是“不”,但我不认为这值得这么多反对。如果您习惯于其他语言并且不容易回答,那么这不是一个愚蠢的问题,除非您想阅读 1000 多页的规范。它可能会更好,因为“我试过这个但它没有用,所以我该如何实现这个”,但即便如此......
  • 奇怪的是cout &lt;&lt; (s + s) 确实 工作,那么为什么不cout &lt;&lt; (s * 2)?没有特别的原因,只是语言没有定义。

标签: c++ string integer cout multiplication


【解决方案1】:
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);
        }

这是一个 ram 友好的解决方案,比使用 stringstreams 或 string::append 快 10 倍

【讨论】:

    【解决方案2】:

    我在 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;
    }
    

    输出: abcabc

    【讨论】:

      【解决方案3】:

      你可以这样做:

      #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;
      }
      

      在 Python 中,您可以像这样将字符串相乘:

      text = "(Your text)"
      print(text*200)
      

      【讨论】:

      • 你可以,但即使 the accepted answer 实现 string*int 也很像这样:不要。对于初学者,请使用 double 和(有条件地)add 方法。
      • Re "system("pause");":这取决于操作系统。意图是什么?在 Windows 上,这可能是无限延迟(直到按下一个键)。在 Linux 上,它在放弃之前可能是 a slight delay“pause: command not found”)。是否打算在看到结果之前避免终端窗口关闭?
      【解决方案4】:

      字符串不能相乘。

      如果 s 是一个字符

      '.'     // This has ASCII code 46
      

      然后

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

      会给你

      '/'     // This has ASCII code 92
      

      【讨论】:

        【解决方案5】:

        没有,std::string 没有 operator *。您可以将 (char, string) 添加到其他字符串。看看这个http://en.cppreference.com/w/cpp/string/basic_string

        如果你想要这种行为(没有建议),你可以使用这样的东西

        #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

        【讨论】:

        • 不应该size_t 而是typename std::basic_string&lt;Char, Traits, Allocator&gt;::size_type 吗?
        • @moooeeeep 应该是,但在这里不是很重要。
        • 为避免进行(或可能进行)多次重新分配,可以使用简单的tmp.reserve(n*s.size()) 或类似名称。我不建议写这样的operator*() - 一个接受字符串和重复计数并返回结果的辅助函数,可以说会更清晰。
        【解决方案6】:

        没有预定义的* 运算符可以将字符串乘以int,但您可以定义自己的:

        #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;
        }
        

        【讨论】:

        • 如果你这样做,你可能也想做operator*(int, std::string const&amp;)
        • 这是一个糟糕的实现。当std::stringappend()operator+= 时,使用流是浪费的
        【解决方案7】:

        std::string 有一个形式的构造函数

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

        这将重复字符。例如

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

        会输出

        ..
        

        【讨论】:

        • 完美优雅
        【解决方案8】:

        它们不能被复用,但我认为您可以编写自己的函数来执行此操作,例如 -

        #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";
        }
        

        虽然这可能不是最好的主意,但对于任何查看代码但没想到这一点的人来说,这会让人非常困惑,

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-26
          • 2015-04-12
          • 2021-03-18
          • 2013-12-17
          • 2021-03-02
          • 1970-01-01
          相关资源
          最近更新 更多