将字符串中的 int 转换为字母;

Converting int in string to letters;

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

我完全没有任何想法,

如何将具有一些数字的字符串转换为具有与此数字一样多的字母的字符串。

例如,如果用户提供像">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