Question

I'm currently writing a function to replace the letters in a line with a corresponding number plus a ",". My current code is:

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 is a my own function). I'm not quite sure how to assign the current letter in the string to a number + a comma. At first I tried just assigning a number to the specific letter but I realised I would need a delimiter so I decided to use a comma.

Was it helpful?

Solution

I guess that what you're trying to achieve is this:

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();
}
  • It looks simpler and more efficient to me to build a new string rather than try to edit the existing one, because since letters (1 char) map to several chars, your initial string would need several inefficient copies and reallocations.
  • To convert from a character to its index, you can use the fact that ASCII characters are naturally ordered and contiguous.
  • You can add protection for non-letter characters, e.g. numbers and most punctuation will return negative indexes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top