user3437351
user3437351

Reputation: 11

String Comparison - Replacing Word in Char Array

I'm writing a function that accepts a char array containing the title of a book as parameter, the following then has to take place:

  1. Extra white spaces between words need to be removed [DONE]**

  2. Text has to be converted to title case, i.e each new word has to start with a capital letter [DONE]

  3. Lastly I have I text file (minors.txt) containing a number of words that should not be capitalized by the function, like "a" and "an", however I don't know how to implement this, any help on how to do this will be much appreciated!

Example:

ENTER THE TITLE OF THE BOOK: a brief hisTOry OF everyTHING

Correct Output:

a Brief History of Everything

Here is my code:

bool Book :: convertToTitleCase(char* inTitle)
{  
  int length = strlen(inTitle);
  bool thisWordCapped = false;   

  //Convert paramater to lower case and
  //Remove multiple white spaces
  for (int x = 0; x < length; x++)
  {
  inTitle[x] = tolower(inTitle[x]);

  if (isspace(inTitle[x]) && isspace(inTitle[x+1]))
  {
      while (isspace(inTitle[x]) && isspace(inTitle[x+1]))
      {
      int i;
      for (i = x + 1; i < length; i++)
      {
          if(i==(length-1))
          {
          inTitle[i] = '\0';
          }
          else
          {
          inTitle[i] = inTitle[i+1];
          }
      }
      }
  }
  }

 /* Read through text file and identify the words that should not be capitalized,
     dont know how, please help! */

 //Capitalize the first letter of each word
 for (int i = 0; i < length; i++)
  {
  if ((ispunct(inTitle[i])) || (isspace(inTitle[i])))
  {
      thisWordCapped = false;
  }

  if ((thisWordCapped==false) && (isalpha(inTitle[i])))
  {
      inTitle[i] = toupper(inTitle[i]);
      thisWordCapped = true;
  }  
  }
  return true;

}

I was thinking of maby reading the words in the text file into a string array, and then comparing the two arrays to ensure that when a word is present in a text file, the word is not capitalized, however I don't know if that is possible between a string array and a char array.

I'm quite clueless as to what to do or how it works, any help would be appreciated, thanks!

PS - I'm still relatively new to C++ so please excuse inefficient code,

Upvotes: 1

Views: 499

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106096

It's better to read the file into a set or unordered_set, rather than an array - something like:

std::set<std::string> words;
if (std::ifstream in("minors.txt"))
{
    std::string word;
    while (in >> word)
        words.insert(word);
}
else
{
    std::cerr << "error reading minors.txt file\n";
    exit(EXIT_FAILURE);
}

Do that once at the start of the program, then before you capitalise a word use words.count(the_word) to see if it needs to be uppercase.

Upvotes: 1

Related Questions