首页 > 解决方案 > 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';
}

标签: c

解决方案


这是一些带有两个修复的解释。

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

推荐阅读