请把它变成一个循环

时间:2021-05-30 18:52:28

标签: c++

我一直在努力使这个循环。任何帮助,将不胜感激。我尝试以多种方式编写循环,但输出总是错误的,这与它在此代码中的工作方式不同。提前致谢。

std::string findConfPass(std::string link) {
  if (link.length() == 64) {
    std::string foundConfPass = link.substr(32, 33);
    return foundConfPass;
  }
  if (link.length() == 65) {
    std::string foundConfPass = link.substr(33, 33);
    return foundConfPass;
  }
  if (link.length() == 66) {
    std::string foundConfPass = link.substr(34, 33);
    return foundConfPass;
  }
  if (link.length() == 67) {
    std::string foundConfPass = link.substr(35, 33);
    return foundConfPass;
  }
  if (link.length() == 68) {
    std::string foundConfPass = link.substr(36, 33);
    return foundConfPass;
  }
  if (link.length() == 69) {
    std::string foundConfPass = link.substr(37, 33);
    return foundConfPass;
  }
  if (link.length() == 70) {
    std::string foundConfPass = link.substr(38, 33);
    return foundConfPass;
  }
  if (link.length() == 71) {
    std::string foundConfPass = link.substr(39, 33);
    return foundConfPass;
  }
  if (link.length() == 72) {
    std::string foundConfPass = link.substr(40, 33);
    return foundConfPass;
  }
  if (link.length() == 73) {
    std::string foundConfPass = link.substr(41, 33);
    return foundConfPass;
  }
  if (link.length() == 74) {
    std::string foundConfPass = link.substr(42, 33);
    return foundConfPass;
  }
  if (link.length() == 75) {
    std::string foundConfPass = link.substr(43, 33);
    return foundConfPass;
  } else {
    std::string foundConfPass = link.substr(43, 33);
    return foundConfPass;
  }
}

最好的方法是什么?

1 个答案:

答案 0 :(得分:4)

使用 size_t len 您的案例是

if (link.length() == len) {
    std::string foundConfPass = link.substr(len-32, 33);
    return foundConfPass;
} 

现在您可以看到 64 <= len <= 75 的所有情况在如上编写时都是相同的。只有其他不同。因此整个函数可以写成:

std::string findConfPass(std::string link) {
    auto len = link.length();
    if (64 <= len && len <= 75) {
         std::string foundConfPass = link.substr(len-32, 33);
         return foundConfPass;
    } else {
         std::string foundConfPass = link.substr(43, 33);
         return foundConfPass;
    }
}

我不知道如何用循环来做同样的事情。我的意思是我可以使用循环来编写一些东西,但它不会像上面那样简单。

请注意,无条件调用 link.substr(43, 33); 是有问题的。您应该检查索引是否有效。我只是向您展示了一种编写与您的代码完全相同的代码的方法。