C 中的类似Python的字符串乘法
Python-like string multiplication in C++
作为长期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;
请参阅实时演示
相关文章:
- 如何将真正的字符串从python c-api转换为python脚本
- 如何在C++中将 Python 字符串转换为其转义版本?
- 从 Python 接收C++字符串
- 我如何在C++像在 Python 中一样实现 f 字符串?
- 如何将 Python 字符串传递给 C++ (extern C) 函数
- C++ python 中的函数返回数字而不是字符串
- C++未知长度字符串的数组,其行为类似于 Python 字符串列表
- 如何在 c++ 中进行 python 样式的字符串切片
- 如何使用 CTypes 将 wchar_t** - 以空结尾的 UNICODE 字符串数组 - 返回到 Python 脚
- 解析 c++ 中的字符串,如 python 的解析包
- 如何通过C++在Python函数中传递字符串参数
- 尝试打印字符串时"Python Exception <class 'gdb.error'> There is no member named _M_dataplus."
- 如何在 Python 或 C++ 中执行任意字符串?
- 使用 ctypes 和 wchar_t 时如何从 C++ 获取字符串到 python?
- QtcpServer:Qt如何获取python字符串进行标记
- 如何在 python 包装中使用 unicode 字符串用于带有 cython 的 c++ 类?
- Qt 如何接收 Python 发送字符串
- 使用Python将C 结构更改为JSON字符串
- 如何在 Python 3 中正确处理用于嵌入的字符串
- 执行 c++ 中字符串中提供的 Python 函数