【问题标题】:words counting in file like linux wc command in C文件中的单词计数,如 C 中的 linux wc 命令
【发布时间】:2012-10-23 20:50:37
【问题描述】:

我正在尝试编写类似于 Linux 命令 wc 的东西来计算任何类型文件中的单词、新行和字节数,而我只能使用 C 函数读取。我已经编写了这段代码,我得到了换行符和字节的正确值,但我没有得到计数字的正确值。

int bytes = 0;
int words = 0;
int newLine = 0;
char buffer[1];
int file = open(myfile,O_RDONLY);
if(file == -1){
  printf("can not find :%s\n",myfile);
}
else{
  char last = 'c'; 
  while(read(file,buffer,1)==1){
    bytes++;
    if(buffer[0]==' ' && last!=' ' && last!='\n'){
      words++;
    }
    else if(buffer[0]=='\n'){
      newLine++;
      if(last!=' ' && last!='\n'){
        words++;
      }
    }
    last = buffer[0];
  }        
  printf("%d %d %d %s\n",newLine,words,bytes,myfile);        
} 

【问题讨论】:

  • 与预期输出相比,您的输出是多少?
  • 你需要一个'inword'布尔值,当你正在阅读一个单词时它是yes,当你不是时它是no;当它变为“in a word”时,您会增加字数。定义适合自己的词。
  • 你知道正则表达式吗?如果是,则搜索 libpcre 并在您的程序中使用它以使其可扩展......否则值得花时间了解它们
  • 这里是how to count words in a string。您可以根据自己的情况进行调整

标签: c count word wc


【解决方案1】:

使用isspace(char ch) 函数检查空格。

int isInWord = 0;/*false*/
while(read(file,buffer,1)==1){
    bytes++ ;
    if(!isspace(buffer[0])){
         isInWord = 1;/*true*/
         continue;
    }else{
      if(buffer[0] == '\n'){
        newLine++;
      }else{
        if(isInWord)
         words++;
      }
      isInWord = 0;
   }
}

【讨论】:

  • 如果文件以非空格结尾,例如"word",则会失败。比较this algorithm
  • 啊,我看到了这个错误。谢谢@J.F.Sebastian
【解决方案2】:

你应该颠倒你的逻辑。与其寻找空格并增加字数,不如寻找非空格来增加字数。此外,它可以帮助使用状态变量而不是查看最后一个字符:

int main(void)
{
   const char *myfile = "test.txt";
   int bytes = 0;
   int words = 0;
   int newLine = 0;
   char buffer[1];
   int file = open(myfile,O_RDONLY);
   enum states { WHITESPACE, WORD };
   int state = WHITESPACE;
   if(file == -1){
      printf("can not find :%s\n",myfile);
   }
   else{
      char last = ' '; 
      while (read(file,buffer,1) ==1 )
      {
         bytes++;
         if ( buffer[0]== ' ' || buffer[0] == '\t'  )
         {
            state = WHITESPACE;
         }
         else if (buffer[0]=='\n')
         {
            newLine++;
            state = WHITESPACE;
         }
         else 
         {
            if ( state == WHITESPACE )
            {
               words++;
            }
            state = WORD;
         }
         last = buffer[0];
      }        
      printf("%d %d %d %s\n",newLine,words,bytes,myfile);        
   } 

}

看起来 wc 有一些关于标点符号不是单词的逻辑,这段代码无法处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2015-05-25
    相关资源
    最近更新 更多