将字符串中的 int 转换为字母;
Converting int in string to letters;
我完全没有任何想法,
如何将具有一些数字的字符串转换为具有与此数字一样多的字母的字符串。
例如,如果用户提供像">B5C5"这样的字符串,我想将其转换为看起来像">BBBBBCCCCC"的字符串。
有没有简单方便的方法可以做到这一点?如有任何线索,我将不胜感激。谢谢
假设输入字符串s
始终是单个字母的序列,后跟一个数字,重复; 下面是 range-v3 的解决方案:
auto to_str = [](auto s) { return rv::repeat_n(s[0], s[1] - '0'); };
auto res = s | rv::chunk(2) | rv::transform(to_str) | rv::join | ranges::to<std::string>;
这是一个演示。
这是我的解决方案,希望对您有所帮助。
#include<iostream>
#include<ctype.h>
#include<string>
using namespace std;
string convert_alphanumeric_to_alpha(string input){
string new_string = "";
string num_to_repeat = "";
for(int i = 0; i < input.length(); i++){
if(isdigit(input[i]) && i < input.length() - 1){
num_to_repeat += input[i];
}else{
if(i == input.length() - 1){
num_to_repeat += input[i];
}
if(num_to_repeat != ""){
int num = stoi(num_to_repeat) - 1;
for(int j = 0; j < num; j++){
new_string += new_string[new_string.length() - 1];
}
num_to_repeat = "";
}
if(!isdigit(input[i])){
new_string += input[i];
}
}
}
return new_string;
}
int main(){
cout << convert_alphanumeric_to_alpha("a2b4c6d8e10f12") << endl;
return 0;
}
输出: aabbbbccccccddddddddeeeeeeeefff
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用