Extracting all-caps variables from string expressionsRegular expressions - match only specified string lengthExtracting numbers before colonExtracting a Decimal from a stringMathematical expressions evaluator with callbacks, the logicExtracting data from a stringParsing string and extracting meaningful informationReturn all valid expressions with specific targetTokenize and detect syntactic errors in simple math expressionsPalindrome from all the substringsRemove excessive whitespace from string

Connection Between Knot Theory and Number Theory

What can I do if I am asked to learn different programming languages very frequently?

Why would five hundred and five same as one?

How to preserve electronics (computers, ipads, phones) for hundreds of years?

Could a welfare state co-exist with mega corporations?

Would this string work as string?

Should I warn a new PhD Student?

What is the purpose of using a decision tree?

Do native speakers use "ultima" and "proxima" frequently in spoken English?

Showing mass murder in a kid's book

Weird lines in Microsoft Word

How do I lift the insulation blower into the attic?

Extract substring according to regexp with sed or grep

Can you describe someone as luxurious? As in someone who likes luxurious things?

Travelling in US for more than 90 days

Friend wants my recommendation but I don't want to give it to him

Why didn't Voldemort know what Grindelwald looked like?

Should a narrator ever describe things based on a character's view instead of facts?

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

Why is "la Gestapo" feminine?

Why do Radio Buttons not fill the entire outer circle?

1 John in Luther’s Bibel

Highest stage count that are used one right after the other?

"Oh no!" in Latin



Extracting all-caps variables from string expressions


Regular expressions - match only specified string lengthExtracting numbers before colonExtracting a Decimal from a stringMathematical expressions evaluator with callbacks, the logicExtracting data from a stringParsing string and extracting meaningful informationReturn all valid expressions with specific targetTokenize and detect syntactic errors in simple math expressionsPalindrome from all the substringsRemove excessive whitespace from string













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 strings






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 10 mins ago









      Jamal

      30.4k11121227




      30.4k11121227










      asked 7 hours ago









      YosemiteYosemite

      405




      405




















          1 Answer
          1






          active

          oldest

          votes


















          3












          $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$












          • $begingroup$
            Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
            $endgroup$
            – Yosemite
            1 min ago










          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%2fextracting-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









          3












          $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$












          • $begingroup$
            Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
            $endgroup$
            – Yosemite
            1 min ago















          3












          $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$












          • $begingroup$
            Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
            $endgroup$
            – Yosemite
            1 min ago













          3












          3








          3





          $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 7 hours ago









          JuhoJuho

          1,266410




          1,266410











          • $begingroup$
            Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
            $endgroup$
            – Yosemite
            1 min ago
















          • $begingroup$
            Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
            $endgroup$
            – Yosemite
            1 min ago















          $begingroup$
          Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
          $endgroup$
          – Yosemite
          1 min ago




          $begingroup$
          Very nice. Right away I tested it and got the right output. After, I stepped through your code with pencil and paper until I got the same answers, to make sure I understood how it worked. Much appreciated.
          $endgroup$
          – Yosemite
          1 min ago

















          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%2fextracting-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

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

          Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar