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
$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');
c++ algorithm strings
$endgroup$
add a comment |
$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');
c++ algorithm strings
$endgroup$
add a comment |
$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');
c++ algorithm strings
$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
c++ algorithm strings
edited 10 mins ago
Jamal♦
30.4k11121227
30.4k11121227
asked 7 hours ago
YosemiteYosemite
405
405
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
$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 hasstd::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());
$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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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 hasstd::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());
$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
add a comment |
$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 hasstd::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());
$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
add a comment |
$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 hasstd::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());
$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 hasstd::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());
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
add a comment |
$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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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