C++ : Extracting all-caps variables from string expressions












2












$begingroup$


I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:



Input: "(A + B) - 2"

Expected Output: { A, B }



Input: "pow(AC,E) * ( E * F )"

Expected Output: { AC, E, F }



The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).



template<class T>
std::vector<std::string> MapEvaluator<T>::extractVariables(std::string expression) {

expression = expression + " ";
std::vector<std::string> variables = {};
std::string substring;
size_t consecutiveCharsCaps = 0;
bool previousCharCaps = false;

for (size_t i = 0; i < expression.length(); i++)
{
if (isCapital(expression[i]))
{
consecutiveCharsCaps++;
previousCharCaps = true;
}
else {
if(previousCharCaps) {
substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps);
variables.push_back(substring);
consecutiveCharsCaps = 0;
previousCharCaps = false;
}
}
}

unique(variables);
return variables;
}

template <class T>
void MapEvaluator<T>::unique(std::vector<std::string> &vec)
{
auto end = vec.end();
for (auto it = vec.begin(); it != end; ++it) {
end = std::remove(it + 1, end, *it);
}
vec.erase(end, vec.end());
}

template<class T>
bool MapEvaluator<T>::isCapital(char c) {
return (c >='A' && c <= 'Z');
}









share|improve this question









$endgroup$

















    2












    $begingroup$


    I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:



    Input: "(A + B) - 2"

    Expected Output: { A, B }



    Input: "pow(AC,E) * ( E * F )"

    Expected Output: { AC, E, F }



    The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).



    template<class T>
    std::vector<std::string> MapEvaluator<T>::extractVariables(std::string expression) {

    expression = expression + " ";
    std::vector<std::string> variables = {};
    std::string substring;
    size_t consecutiveCharsCaps = 0;
    bool previousCharCaps = false;

    for (size_t i = 0; i < expression.length(); i++)
    {
    if (isCapital(expression[i]))
    {
    consecutiveCharsCaps++;
    previousCharCaps = true;
    }
    else {
    if(previousCharCaps) {
    substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps);
    variables.push_back(substring);
    consecutiveCharsCaps = 0;
    previousCharCaps = false;
    }
    }
    }

    unique(variables);
    return variables;
    }

    template <class T>
    void MapEvaluator<T>::unique(std::vector<std::string> &vec)
    {
    auto end = vec.end();
    for (auto it = vec.begin(); it != end; ++it) {
    end = std::remove(it + 1, end, *it);
    }
    vec.erase(end, vec.end());
    }

    template<class T>
    bool MapEvaluator<T>::isCapital(char c) {
    return (c >='A' && c <= 'Z');
    }









    share|improve this question









    $endgroup$















      2












      2








      2





      $begingroup$


      I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:



      Input: "(A + B) - 2"

      Expected Output: { A, B }



      Input: "pow(AC,E) * ( E * F )"

      Expected Output: { AC, E, F }



      The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).



      template<class T>
      std::vector<std::string> MapEvaluator<T>::extractVariables(std::string expression) {

      expression = expression + " ";
      std::vector<std::string> variables = {};
      std::string substring;
      size_t consecutiveCharsCaps = 0;
      bool previousCharCaps = false;

      for (size_t i = 0; i < expression.length(); i++)
      {
      if (isCapital(expression[i]))
      {
      consecutiveCharsCaps++;
      previousCharCaps = true;
      }
      else {
      if(previousCharCaps) {
      substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps);
      variables.push_back(substring);
      consecutiveCharsCaps = 0;
      previousCharCaps = false;
      }
      }
      }

      unique(variables);
      return variables;
      }

      template <class T>
      void MapEvaluator<T>::unique(std::vector<std::string> &vec)
      {
      auto end = vec.end();
      for (auto it = vec.begin(); it != end; ++it) {
      end = std::remove(it + 1, end, *it);
      }
      vec.erase(end, vec.end());
      }

      template<class T>
      bool MapEvaluator<T>::isCapital(char c) {
      return (c >='A' && c <= 'Z');
      }









      share|improve this question









      $endgroup$




      I'm extracting variables from user entered mathematical expressions, so that I can enter them into the expression evaluator exprtk. For now, the condition is given that variable names will be composed of consecutive capital letters. Any mathematical constants or function names will be lowercase. Some hypothetical inputs and expected outputs:



      Input: "(A + B) - 2"

      Expected Output: { A, B }



      Input: "pow(AC,E) * ( E * F )"

      Expected Output: { AC, E, F }



      The code I have right now seems to work, but I would love a critique. I add a space to the end of the string to make my algorithm catch cases at the end of the string, which seems a bit hacky(?).



      template<class T>
      std::vector<std::string> MapEvaluator<T>::extractVariables(std::string expression) {

      expression = expression + " ";
      std::vector<std::string> variables = {};
      std::string substring;
      size_t consecutiveCharsCaps = 0;
      bool previousCharCaps = false;

      for (size_t i = 0; i < expression.length(); i++)
      {
      if (isCapital(expression[i]))
      {
      consecutiveCharsCaps++;
      previousCharCaps = true;
      }
      else {
      if(previousCharCaps) {
      substring = expression.substr(i - consecutiveCharsCaps, consecutiveCharsCaps);
      variables.push_back(substring);
      consecutiveCharsCaps = 0;
      previousCharCaps = false;
      }
      }
      }

      unique(variables);
      return variables;
      }

      template <class T>
      void MapEvaluator<T>::unique(std::vector<std::string> &vec)
      {
      auto end = vec.end();
      for (auto it = vec.begin(); it != end; ++it) {
      end = std::remove(it + 1, end, *it);
      }
      vec.erase(end, vec.end());
      }

      template<class T>
      bool MapEvaluator<T>::isCapital(char c) {
      return (c >='A' && c <= 'Z');
      }






      c++ algorithm






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 6 hours ago









      YosemiteYosemite

      385




      385






















          1 Answer
          1






          active

          oldest

          votes


















          2












          $begingroup$

          Some observations:




          • It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.


          • Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.


          • There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.



          So with these in mind, we can re-write your function to e.g.,:



          std::vector<std::string> get_variables(const std::string& str)
          {
          std::set<std::string> vars;

          for (auto first = str.cbegin(); first != str.cend(); )
          {
          auto var_end = std::adjacent_find(first, str.cend(),
          (char a, char b) { return std::isupper(a) != std::isupper(b); });

          if (var_end != str.cend())
          {
          ++var_end;
          }

          if (is_capital(*first))
          {
          vars.insert(std::string(first, var_end));
          }

          first = var_end;
          }

          return std::vector<std::string>(vars.cbegin(), vars.cend());
          }





          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215793%2fc-extracting-all-caps-variables-from-string-expressions%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2












            $begingroup$

            Some observations:




            • It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.


            • Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.


            • There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.



            So with these in mind, we can re-write your function to e.g.,:



            std::vector<std::string> get_variables(const std::string& str)
            {
            std::set<std::string> vars;

            for (auto first = str.cbegin(); first != str.cend(); )
            {
            auto var_end = std::adjacent_find(first, str.cend(),
            (char a, char b) { return std::isupper(a) != std::isupper(b); });

            if (var_end != str.cend())
            {
            ++var_end;
            }

            if (is_capital(*first))
            {
            vars.insert(std::string(first, var_end));
            }

            first = var_end;
            }

            return std::vector<std::string>(vars.cbegin(), vars.cend());
            }





            share|improve this answer









            $endgroup$


















              2












              $begingroup$

              Some observations:




              • It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.


              • Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.


              • There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.



              So with these in mind, we can re-write your function to e.g.,:



              std::vector<std::string> get_variables(const std::string& str)
              {
              std::set<std::string> vars;

              for (auto first = str.cbegin(); first != str.cend(); )
              {
              auto var_end = std::adjacent_find(first, str.cend(),
              (char a, char b) { return std::isupper(a) != std::isupper(b); });

              if (var_end != str.cend())
              {
              ++var_end;
              }

              if (is_capital(*first))
              {
              vars.insert(std::string(first, var_end));
              }

              first = var_end;
              }

              return std::vector<std::string>(vars.cbegin(), vars.cend());
              }





              share|improve this answer









              $endgroup$
















                2












                2








                2





                $begingroup$

                Some observations:




                • It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.


                • Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.


                • There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.



                So with these in mind, we can re-write your function to e.g.,:



                std::vector<std::string> get_variables(const std::string& str)
                {
                std::set<std::string> vars;

                for (auto first = str.cbegin(); first != str.cend(); )
                {
                auto var_end = std::adjacent_find(first, str.cend(),
                (char a, char b) { return std::isupper(a) != std::isupper(b); });

                if (var_end != str.cend())
                {
                ++var_end;
                }

                if (is_capital(*first))
                {
                vars.insert(std::string(first, var_end));
                }

                first = var_end;
                }

                return std::vector<std::string>(vars.cbegin(), vars.cend());
                }





                share|improve this answer









                $endgroup$



                Some observations:




                • It seems that std::adjacent_find essentially already does what you want, which is extracting all continuous sub-strings consisting of uppercase letters.


                • Removing duplicates from a vector might be fine, but you can also avoid this completely by inserting the found elements into a std::set. I suspect that the number of unique variables is always small, so this is a cleaner approach.


                • There is no reason for isCapital to be a member function. Instead, it should be a free function. Remember that interfaces should be complete but minimal. But in fact, there's no reason for the function in the first place: the standard already has std::isupper that we should rather use.



                So with these in mind, we can re-write your function to e.g.,:



                std::vector<std::string> get_variables(const std::string& str)
                {
                std::set<std::string> vars;

                for (auto first = str.cbegin(); first != str.cend(); )
                {
                auto var_end = std::adjacent_find(first, str.cend(),
                (char a, char b) { return std::isupper(a) != std::isupper(b); });

                if (var_end != str.cend())
                {
                ++var_end;
                }

                if (is_capital(*first))
                {
                vars.insert(std::string(first, var_end));
                }

                first = var_end;
                }

                return std::vector<std::string>(vars.cbegin(), vars.cend());
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 6 hours ago









                JuhoJuho

                1,241410




                1,241410






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215793%2fc-extracting-all-caps-variables-from-string-expressions%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    Is this a new Fibonacci Identity?

                    19世紀