C 中的类似Python的字符串乘法

Python-like string multiplication in C++

本文关键字:字符串 Python      更新时间:2023-10-16

作为长期Python程序员,我非常感谢Python的字符串乘法功能,例如:

> print("=" * 5)  # =====

因为C std::string s没有*超载,所以我设计了以下代码:

#include <iostream>
#include <string>

std::string operator*(std::string& s, std::string::size_type n)
{
  std::string result;
  result.resize(s.size() * n);
  for (std::string::size_type idx = 0; idx != n; ++idx) {
    result += s;
  }
  return result;
}

int main()
{
  std::string x {"X"};
  std::cout << x * 5; // XXXXX
}

我的问题:这可以做更多的惯用/有效(还是我的代码甚至有缺陷)?

简单地将正确的构造函数用于您的简单示例:

std::cout << std::string(5, '=') << std::endl; // Edit!

对于真正的乘以字符串您应该使用简单的内联函数(和 reserve() 避免多个重新分配)

std::string operator*(const std::string& s, size_t n) {
    std::string result;
    result.reserve(s.size()*n);
    for(size_t i = 0; i < n; ++i) {
        result += s;
    }
    return result;
}

并使用它

std::cout << (std::string("=+") * 5) << std::endl;

请参阅实时演示