c - String-fun_to_remove 一条评论
问题描述
我有一个删除评论的功能,或者多个,但我不明白它是如何工作的。
循环如何工作?有
for(j+=2; s[++j] && (s[j-1]!='*' || s[j]!='/' || !j++); );
为什么 !j++ 有效?
#include <stdio.h>
void remove_cmmnt(char *s)
{ int k=0;
char *p=s;
for( k=0;p[k];k++);
char T[k];
int i,j;
for(i=j=0; s[j] ; )
{
if(s[j]=='/' && s[j+1]=='*')
for(j+=2; ++j && (s[j-1]!='*' || s[j]!='/' || !j++); );
else
T[i++]=s[j++];
}
printf("%s",T);
s[i]='\0';
}
解决方案
这是一些带有两个修复的解释。
#include <stdio.h>
void remove_cmmnt(char *s)
{
int k=0;
char *p=s; // The additional pointer is unnecessary, you could use 's' instead of 'p' in the next line.
for( k=0;p[k];k++); // the same as k = strlen(s); probably one byte too short for array size
k++; // added to fix wrong array size
char T[k]; // array should be big enough to hold original string including '\0'
int i,j; // j is source index, i is destination index
for(i=j=0; // initialize source and destination index
s[j] // terminate loop if we reached end of source string
; ) // no explicit incrementing of a loop index
{
if(s[j]=='/' && s[j+1]=='*') // start of comment at current and next position. We can check 2 characters because the loop condition already checked for not '\0' and at least the terminating '\0' should follow.
for(j+=2; // skip 2 characters ('/' and '*')
// The complicated condition with index incrementing makes use of short-circuit evaluation
s[++j] && // always evaluated. increment index, terminate loop if end of string is reached.
(s[j-1]!='*' || // continue loop and stop evaluating condition if previous character is not 1st char '*' of comment termination
s[j]!='/' || // continue loop and stop evaluating condition if current char is not 2nd char '/' of comment termination
!j++) // This is reached only if we found the end of the comment. Increment index and (because normally j!=0) evaluate as false to terminate the loop. This skips the terminating '/' we have just found.
; ); // no explicit incrementing of a loop index
else // if we didn't find a comment start
T[i++]=s[j++]; // copy current character from original to modified copy
}
T[i]='\0'; // T instead of s as in the question and before printf. terminate modified copy.
printf("%s",T);
}
推荐阅读
- c# - 在 ASP.Net 中找不到资源错误
- javascript - 如何匹配 URL 但不是模式
- c# - 在 ASP.Net MVC 中使用 JSON 从 AngularJS 调用 MVC 控制器
- c# - 使用附加模式属性后,iText7 将签名转换为不可见签名
- python - 如何使用 selenium python 验证 html5 验证
- python - 在python中合并两个字符串
- performance - Android Studio 加载大数据以在 Recyclerview 中显示
- node.js - 上传新命令后,Discord.js 应用程序在启动时不断崩溃
- python - 退格 \n \t 在长字符串 python argparse 中不起作用
- javascript - 如何在 POST 方法中使用 dns.lookup()?