Abbreviations, simple: Difference between revisions

m
Reformatted C++ code
(→‎{{header|Wren}}: Now uses 'fmt' module.)
m (Reformatted C++ code)
Line 254:
{
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
 
// cmd is assumed to be all uppercase
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len)
{
}
Line 272:
bool command::match(const std::string& str) const
{
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
 
bool parse_integer(const std::string& word, int& value)
{
try
{
{
size_t pos;
int i = std::stoi(word, &pos, 10);
if (pos < word.length())
return false;
value = i;
return true;
}
}
catch (const std::exception& ex)
{
{
return false;
}
}
}
 
Line 297:
void uppercase(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
 
Line 304:
{
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
 
command_list::command_list(const char* table)
{
std::istringstream is(table);
std::string word;
std::vector<std::string> words;
while (is >> word)
{
{
uppercase(word);
words.push_back(word);
}
}
for (size_t i = 0, n = words.size(); i < n; ++i)
{
{
word = words[i];
// if there's an integer following this word, it specifies the minimum
// length for the command, otherwise the minimum length is the length
// of the command string
int len = word.length();
if (i + 1 < n && parse_integer(words[i + 1], len))
++i;
commands_.push_back(command(word, len));
}
}
}
 
const command* command_list::find_command(const std::string& word) const
{
for (const command& command : commands_)
{
{
if (command.match(word))
return &command;
}
}
return nullptr;
}
 
std::string test(const command_list& commands, const std::string& input)
{
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word)
{
{
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
}
return output;
}
 
int main()
{
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}</lang>
 
1,777

edits