下面是编程之家 jb51.cc 通过网络收集整理的代码片段。
编程之家小编现在分享给大家,也给大家做个参考。
一种解法非常好:状态机。在各种状态之间跳转,逻辑清晰,不易出错,出错了也容易调试。
#include
int state;
int c1,c2;
void change_state(int c);
int main(int argc,const char * argv[]) {
int c;
state = 0;
c1 = 0;
c2 = 0;
while ((c=getchar())!=EOF) {
c1 = c2;
c2 = c;
change_state(c);
}
if (/* DISABLES CODE */ (0)==1) {
printf("just test://abcd");
printf("just test:/*hello*/");
}
}
/*状态机函数*/
void change_state(int c){
if (state==0) {//普通状态
if (c=='/') {
state = 1;
}else if (c=='"'){
state = 5;
putchar(c);
}else if (c=='\''){
state = 6;
putchar(c);
}
else{
state = 0;
putchar(c);
}
}else if (state==1) {//检测到1个'/'
if (c=='/') {
state = 2;
}else if (c=='*'){
state = 3;
}else{
state = 0;
putchar(c1);
putchar(c);
}
}else if (state==2) {// "//"注释状态
if (c=='\n') {
state = 0;
putchar(c);
}else{
state = 2;
}
}else if (state==3) {// "/*"注释状态
if (c=='*') {
state = 4;
}else{
state = 3;
}
}else if (state==4) {
if (c=='/') {
state = 0;
}else{
state = 3;
}
}else if (state==5){//在"字符串里
if (c=='"') {
state = 0;
putchar(c);
}else if(c=='\\'){
state = 7;
putchar(c);
}else{
state = 5;
putchar(c);
}
}else if (state==6){//在'字符里
if (c=='\'') {
state = 0;
putchar(c);
}else if(c=='\\'){
state = 8;
putchar(c);
}else{
state = 6;
putchar(c);
}
}else if (state==7){//在"字符串里的"\"
state = 5;
putchar(c);
}else if (state==8){//在'字符串里的"\"
state = 6;
putchar(c);
}
}
以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
小编个人微信号 jb51ccc
喜欢与人分享编程技术与工作经验,欢迎加入编程之家官方交流群!