fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4. #include <cstring>
  5. #include <set>
  6. #include <sstream>
  7.  
  8. std::string tolower( std::string str )
  9. { for( char& c : str ) c = std::tolower(c) ; return str ; }
  10.  
  11. std::string remove_punct( const std::string& str )
  12. {
  13. std::string result ;
  14. for( char c : str ) if( !std::ispunct(c) ) result += c ;
  15. return result ;
  16. }
  17.  
  18. std::string capitalise( std::string str )
  19. { if( !str.empty() ) str[0] = std::toupper( str[0] ) ; return str ; }
  20.  
  21. // http://w...content-available-to-author-only...s.com/reference/set/set/
  22. char* convert_to_title_case( char* title, const std::set<std::string>& nocap_words )
  23. {
  24. std::string converted_title ;
  25.  
  26. // http://w...content-available-to-author-only...s.com/reference/sstream/istringstream/
  27. std::istringstream stm(title) ;
  28. std::string word ;
  29. while( stm >> word ) // for each word in the title
  30. {
  31. word = tolower(word) ;
  32. if( !converted_title.empty() ) converted_title += ' ' ;
  33.  
  34. // capitalise it if it is not in the nocap_words set
  35. // http://w...content-available-to-author-only...s.com/reference/set/set/find/
  36. if( nocap_words.find( remove_punct(word) ) == nocap_words.end() )
  37. word = capitalise(word) ;
  38.  
  39. converted_title += word ;
  40. }
  41.  
  42. // copy converted_title back into the c-style string and return
  43. return std::strcpy( title, converted_title.c_str() ) ;
  44. }
  45.  
  46. std::set<std::string> get_words( std::istream& stm )
  47. {
  48. std::set<std::string> result ;
  49. std::string w ;
  50. while( stm >> w ) result.insert(w) ;
  51. return result ;
  52. }
  53.  
  54. int main()
  55. {
  56. std::istringstream minors( "a an for of the" ) ; // std::ifstream over "minors.txt"
  57. const auto nocap_words = get_words( minors ) ;
  58.  
  59. char test[] [100] = { "a brief hisTOry OF everyTHING", "A Universal HisTOry Of infamy",
  60. "The; history, of: punctuations!", "1024: FOR A history Of NUMBERS" } ;
  61. for( char* title : test )
  62. {
  63. std::cout << title << " => " ;
  64. std::cout << convert_to_title_case( title, nocap_words ) << '\n' ;
  65. }
  66. }
  67.  
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
a brief hisTOry OF everyTHING => a Brief History of Everything
A Universal HisTOry Of infamy => a Universal History of Infamy
The; history, of: punctuations! => the; History, of: Punctuations!
1024: FOR A history Of NUMBERS => 1024: for a History of Numbers