25. Capitalizing an article title

The function template capitalize(), implemented as follows, works with strings of any type of characters. It does not modify the input string but creates a new string. To do so, it uses an std::stringstream. It iterates through all the characters in the input string and sets a flag indicating a new word to true every time a space or punctuation is encountered. Input characters are transformed to uppercase when they represent the first character in a word and to lowercase otherwise:

template <class Elem>
using tstring = std::basic_string<Elem, std::char_traits<Elem>,
std::allocator<Elem>>;
template <class Elem>
using tstringstream = std::basic_stringstream<
Elem, std::char_traits<Elem>, std::allocator<Elem>>;

template <class Elem>
tstring<Elem> capitalize(tstring<Elem> const & text)
{
tstringstream<Elem> result;
bool newWord = true;
for (auto const ch : text)
{
newWord = newWord || std::ispunct(ch) || std::isspace(ch);
if (std::isalpha(ch))
{
if (newWord)
{
result << static_cast<Elem>(std::toupper(ch));
newWord = false;
}
else
result << static_cast<Elem>(std::tolower(ch));
}
else result << ch;
}
return result.str();
}

In the following program you can see how this function is used to capitalize texts:

int main()
{
using namespace std::string_literals;
assert("The C++ Challenger"s ==
capitalize("the c++ challenger"s));
assert("This Is An Example, Should Work!"s ==
capitalize("THIS IS an ExamplE, should wORk!"s));
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset