zl程序教程

您现在的位置是:首页 >  工具

当前栏目

实现去除c语言注释的小工具

工具语言 实现 注释 去除
2023-06-13 09:15:18 时间

去除C代码中的注释,
1.单行注释//;
2.多行注释/**/;
3.单行注释以“\”结尾则下一行也为注释;
4.字符串中的注释不处理。
说是C语言,但其实所有C语系的都可以,比如Java。


小工具:去除C语言注释 

复制代码代码如下:

#include<stdio.h>

intmain(intargc,char*argv[]){
 enum{
   literal,
   single,
   multiple,
   string
 }mode=literal;
 charlast=0,current;

 while((current=getchar())!=EOF){
   switch(mode){
   casesingle:{
     if(last!="\\"&&(current=="\n"||current=="\r")){
       putchar(current);
       current=0;
       mode=literal;
     }
   }break;
   casemultiple:{
     if(last=="*"&&current=="/"){
       current=0;
       mode=literal;
     }
   }break;
   casestring:{
     if(last=="\\"){
       putchar(last);
       putchar(current);
     }elseif(current!="\\"){
       putchar(current);
       if(current=="""){
         mode=literal;
       }
     }
   }break;
   default:{
     if(last=="/"){
       if(current=="/"){
         mode=single;
       }elseif(current=="*"){
         mode=multiple;
       }else{
         putchar(last);
         putchar(current);
       }
     }elseif(current!="/"){
       putchar(current);
       if(current=="""){
         mode=string;
       }
     }
   }break;
   }
   last=current;
 }

 return0;
}

测试代码

复制代码代码如下:


#include<stdlib.h>
#include<stdio.h>

intmain(intargc,char*argv[])
{
//notshow\
notshow\
notshow
//notshow
/*notshow*/
   intis;//notshow
   int/*notshow*/ms;/*notshow*/
   doubleds;//notshow\
   notshow\
   notshow
   doubledm;/*...
   notshow
   notshow*/floatfs;/**
                          *nowshow
                          */
   float/**/fm;
   charcs[]="aaa///***/";
   charcm1[]=/*notshow*/"hello*/";
   charcm2[]="/*redraiment"/*notshow*/;
   /*printf("/////");*/
   returnEXIT_SUCCESS;
}

处理后的代码

复制代码代码如下:
#include<stdlib.h>
#include<stdio.h>

intmain(intargc,char*argv[])
{

 

   intis;
   intms;
   doubleds;
   doubledm; floatfs;
   floatfm;
   charcs[]="aaa///***/";
   charcm1[]="hello*/";
   charcm2[]="/*redraiment";

   returnEXIT_SUCCESS;
}