有没有办法在C++中实现 Python 的 join()?
Is there a way to implement Python's join() in C++?
我正在尝试将密码管理器中的某些功能移植到C 中,但是我想将其移植到C 等效的情况下。我希望至少实现与C
的这2行代码接近t = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
key = ''.join([secrets.choice(t) for _ in range(20)])
#include "common.h"
#include <iostream>
std::string Common::ascii_lowercase() {
std::string ascii_lowercase;
for (char c = 97; c <= 122; c++)
ascii_lowercase += c;
return ascii_lowercase;
}
std::string Common::ascii_uppercase() {
std::string result;
for (char c = 65; c <= 90; c++)
result += c;
return result;
}
std::string Common::digits(){
std::string digits;
for (int i = 0; i <= 9; i++) {
digits += std::to_string(i);
}
return digits;
}
std::string Common::punctuation() {
std::string punctuation;
for (int i = 33; i <= 47; i++)
punctuation += i;
for (int j = 58; j <= 64; j++)
punctuation += j;
for (int z = 91; z <= 96; z++)
punctuation += z;
return punctuation;
}
您可以创建一个函数 join()
,该函数将采用您的序列和要使用的分离器,并返回python方法所使用的函数。
示例:
std::string join(const std::vector<std::string> & sequence, const std::string & separator)
{
std::string result;
for(size_t i = 0; i < sequence.size(); ++i)
result += sequence[i] + ((i != sequence.size()-1) ? separator : "");
return result;
}
您可以按以下方式使用它:
std::vector<std::string> seq {"One", "Two", "Three", "Four"};
std::cout << join(seq, "--") << std::endl;
输出将是:
一二 - 四分之二 - 四个
当然,您可以使用除std::vector
以外的其他容器,这只是一个例子。
我希望它对您有帮助。
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- Pybind11:将元组列表从Python传递到C++
- 如何在c++中使用引用实现类似python的行为
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 递归列出所有目录中的C++与Python与Ruby的性能
- IPC使用多个管道和分支进程来运行Python程序
- 从python中调用C++函数并获取返回值
- Python 3.7 和 excess_args 的 SWIG 问题
- Python中的for循环与C++有何不同
- 使用Pybind11向Python公开Eigen::张量
- 在std::thread中,joinable()然后join()线程安全吗
- Python str to C++ to Python str
- 如何使用Python从C++中读取谷物序列化数据
- 如何在C++中使用pybind11加载一个pickle python列表
- 如何在c++中使用system()来运行包含空格的python脚本
- python集合的C++等价物是什么.计数器
- 如果C++对象的类在另一个boost模块中声明,如何使用boost将指向该对象的指针返回到python
- 有没有办法在C++中实现 Python 的 join()?
- Python 相当于 QList c++ 的 join
- 有没有办法在C++中实现Python的"separator".join()的模拟?