【问题标题】:String Comparison - Replacing Word in Char Array字符串比较 - 替换字符数组中的单词
【发布时间】:2014-07-31 12:08:26
【问题描述】:

我正在编写一个函数,它接受一个包含书名的 char 数组作为参数,然后必须执行以下操作:

  1. 需要删除单词之间的多余空格 [DONE]**

  2. 文本必须转换为标题大小写,即每个新词必须以大写字母 [DONE] 开头

  3. 最后,我有一个文本文件 (minors.txt),其中包含许多不应被函数大写的单词,例如“a”和 “an”,但是我不知道如何实现这一点,有关如何实现的任何帮助 这样做将不胜感激!

示例:

输入书名:万物简史

正确的输出:

万物简史

这是我的代码:

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;

}

我正在考虑将文本文件中的单词读入字符串数组,然后比较两个数组以确保当文本文件中存在单词时,该单词不大写,但我没有知道在字符串数组和字符数组之间是否可行。

我不知道该做什么或它是如何工作的,任何帮助将不胜感激,谢谢!

PS - 我对 C++ 还是比较陌生,所以请原谅低效的代码,

【问题讨论】:

    标签: c++ arrays string comparison compare


    【解决方案1】:

    最好将文件读入setunordered_set,而不是数组 - 类似于:

    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);
    }
    

    在程序开始时执行一次,然后在大写单词之前使用words.count(the_word) 来查看它是否需要大写。

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 2016-06-10
      • 2020-11-09
      • 2015-07-03
      • 1970-01-01
      相关资源
      最近更新 更多