Bob 3: one iteration through a string

This commit is contained in:
Dmitry Kokorin 2016-02-22 00:13:25 +03:00
parent 454f754195
commit 40834ece6e
2 changed files with 20 additions and 35 deletions

View file

@ -7,47 +7,32 @@
namespace bob { namespace bob {
using namespace std;
namespace {
void trim_spaces(string &str)
{
str.erase(remove_if(str.begin(), str.end(),
[](char c){return isspace(static_cast<unsigned char>(c));}),
str.end());
}
string to_uppercase(const string &str)
{
string result = str;
for (auto & c: result)
c = toupper(c);
return result;
}
bool has_alpha(const string &str)
{
return find_if(str.begin(), str.end(),
[](char c){return isalpha(static_cast<unsigned char>(c));}) != str.end();
}
}
const char * hey(const char input[]) const char * hey(const char input[])
{ {
using namespace std;
string str(input); const string str(input);
trim_spaces(str);
if (str.empty()) string::const_reverse_iterator i;
i = find_if(str.crbegin(), str.crend(), [](char c){return !isspace(c);});
if (i == str.crend())
return "Fine. Be that way!"; return "Fine. Be that way!";
if (has_alpha(str) && str == to_uppercase(str)) bool is_question = *i == '?';
i = find_if(i, str.crend(), [](char c){return isalpha(c);});
bool has_alpha = i != str.crend();
bool is_uppercase = all_of(i, str.crend(),
[](char c){return isupper(c) || !isalpha(c);});
if (has_alpha && is_uppercase)
return "Whoa, chill out!"; return "Whoa, chill out!";
if ('?' == str.back()) if (is_question)
return "Sure."; return "Sure.";
return "Whatever."; return "Whatever.";

View file

@ -1,8 +1,8 @@
#pragma once #pragma once
#define EXERCISM_RUN_ALL_TESTS true #define EXERCISM_RUN_ALL_TESTS
namespace bob namespace bob
{ {
const char * hey(const char str[]); const char * hey(const char input[]);
} }