Search code examples
c++stringfunctionreplacealphabet

Replace every letter with its position in the alphabet for a given string


The first step, I changed the string to a lowercase, after that I removed all the non letters from the string, now I am struggling to replace each letter with the alphabet position. does anyone know how to do such a thing? Thank you!

string alphabet_position(string message){
   string alphabet= "abcdefghijklmnopqrstuvwxyz";
   int aplha_numbers[100];

 for_each(message.begin(), message.end(), [](char & c){
     c = ::tolower(c);
 });

 for(int i=0; i< message.size(); i++){

     if(message[i] < 'a' || message[i] > 'z'){
         message.erase(i, 1);
         i--;
     }
 }
for(int j=0; j<message.size(); j++){
    int index = alphabet.find(message[j]);
     aplha_numbers[j]= index +1;


}
std::ostringstream os;
for(int z: aplha_numbers){
    os<<z;
}
std::string str(os.str());

return str;
}

Now I have a different issue , I am getting the alphabet positions but I also get a lot of garbage values after the last letter. As an example Input: abc output 123 and after that a lot of numbers 32761004966.....


Solution

  • There are a few issues in your code:

    1. Your main bug was that in this line:

      for (int z : aplha_numbers)

      You go over all the 100 elements in the allocated array, not just the valid entries. In my solution there's no need for such an array at all. The stringstream objec is updated directly.

    2. The position of a lower case character c is simply c-'a'+1. No need for a lookup table (at least assuming ascii input).

    3. There's no need to actually change the input string by making it a lower case. This can be done on the fly as you traverse it.

    Here's a complete fixed version:

    #include <string>
    #include <sstream>
    #include <iostream>
    #include <cctype>
    
    std::string alphabet_position(std::string message) 
    {
        std::ostringstream os;
        for (auto const & c : message)
        {
            char c_lower = std::tolower(c);
            if (c_lower < 'a' || c_lower > 'z')  continue;
            int pos = c_lower - 'a' + 1;
            os << pos;
        }
        return os.str();
    }
    
    int main()
    {
        std::string s_in = "AbC";
        std::string s_out = alphabet_position(s_in);
        std::cout << "in:" << s_in << ", out:" << s_out << std::endl;
        return 0;
    }
    

    Output:

    in:AbC, out:123
    

    A side note: it's better to avoid using namespace std;. See here: Why is "using namespace std;" considered bad practice?