在字符串中设置一个等于 int + "," 的某个字母

set a certain letter in a string equal to an int + ","

本文关键字:int 设置 字符串 一个      更新时间:2023-10-16

我目前正在编写一个函数,用相应的数字加上","替换一行中的字母。我当前的代码是:

std::string letterToNumber(std::string message) {
  std::string::iterator iter;
  toUpper(message);
  for (iter = message.begin(); iter != message.end(); ++iter) {
    for (int i = 0; i < alphabetSize; ++i) {
      if (*iter == alphabet[i]) {
        // Problem here
      }
    }
  }
  return message;
}

(toUpper是我自己的函数)。我不太确定如何将字符串中的当前字母分配给数字+逗号。起初我尝试只为特定字母分配一个数字,但我意识到我需要一个分隔符,所以我决定使用逗号。

我想您要实现的是:

std::string letterToNumber(std::string input) {
  toUpper(input);
  std::stringstream output;
  std::string::iterator it;
  for (it = input.begin(); it != input.end(); ++it) {
      if (input.begin() != it) {
        output << ",";
      }
      int letterIndex = static_cast<int>(*it) - 'A';
      output << letterIndex;
  }
  return output.str();
}
  • 对我来说,构建一个新字符串而不是尝试编辑现有字符串看起来更简单、更高效,因为由于字母 (1 个字符) 映射到多个字符,因此您的初始字符串需要几个低效的副本和重新分配。
  • 若要从字符转换为其索引,可以使用 ASCII 字符自然有序且连续的事实。
  • 您可以为非字母字符添加保护,例如数字和大多数标点符号将返回负索引