【问题标题】:how to convert a string of number with trailing x's into a list of unsigned numbers如何将带有尾随x的数字字符串转换为无符号数字列表
【发布时间】:2019-08-15 09:48:59
【问题描述】:

我需要将 4 个字符的字符串转换为无符号数字列表 例如 222X = [2220, 2221, 2222, 2223, 2224, 2225, 2226, 2227, 2228, 2229] 类似地,我应该能够转换 22XX(100 个数字)、2XXX(应该产生 1000 个)数字。 有没有快速的方法。

我有以下解决方案,但不是很干净..

std::list<unsigned> stringToCode(std::string fn)
{
   std::list<unsigned> codes;
   unsigned count = std::count(fn.begin(), fn.end(), 'X');

   unsigned none_x = std::stoi(fn);
   unsigned numbers_to_generate = std::pow(10, count);

   unsigned overrule = none_x * numbers_to_generate;
   for (int i = 0; i < numbers_to_generate; i++) {
      unsigned fnumber = none_x * std::pow(10, count) + i;

      codes.push_back(fnumber);
   }

   return codes;
  }

int main() 
{

  std::string number = "4XXX";

  std::list<unsigned> codes = stringToCode(number);

   for (const auto code : codes) {
      std::cout << code << std::endl;
   }

   return 0;
}

【问题讨论】:

  • 看起来很有趣....请给我看代码
  • “有没有快速的方法。” 一定要写一个合适的算法来用某些数字替换 X。
  • 欢迎来到 Stack Overflow。请收下Tour,学习How To Ask a Good Question
  • 2X1XX123 也可以吗?
  • @ThomasSablik 不,X 只出现在末尾。

标签: c++ arrays string int


【解决方案1】:

创建两个变量:

std::string maxVal = fn; 
std::replace(maxVal, 'X', '9'); 
std::string minVal = fn;
std::replace(minVal, 'X', '0');

现在你可以循环使用

for (auto i = std::stoi(minVal), j = std::stoi(maxVal); i <= j; ++i) {
    codes.push_back(i);
}

整个代码

#include <algorithm>
#include <iostream>
#include <list>

std::list<unsigned> stringToCode(std::string fn) {
   std::string maxVal = fn; 
   std::replace(std::begin(maxVal), std::end(maxVal), 'X', '9'); 
   std::string minVal = fn;
   std::replace(std::begin(minVal), std::end(minVal), 'X', '0');
   std::list<unsigned> codes;
   for (auto i = std::stoi(minVal), j = std::stoi(maxVal); i <= j; ++i) {
       codes.push_back(i);
   }

   return codes;
}

int main() {
  std::string number = "4XXX";

  std::list<unsigned> codes = stringToCode(number);

   for (const auto code : codes) {
      std::cout << code << std::endl;
   }

   return 0;
}

【讨论】:

    猜你喜欢
    • 2010-09-22
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多