Remove all comments from a C program and handle quoted strings and character constants - C String

C examples for String:String Function

Description

Remove all comments from a C program and handle quoted strings and character constants

Demo Code

#include <stdio.h>

#define MAXLENGTH 5000/*from w w w  .j a v a2 s .  co  m*/

int main(void){
    int len, i= 0;
    char s[MAXLENGTH] = "this is a test. this is /*a t*/est. this is /*a test.*/ \"this is a test.\" this is a test. ";

    while (s[i] != '\0') {
        if (s[i] == '/' && s[i+1] == '/') {
            i += 2;
            while (s[i] != '\n' && s[i] != '\0')
                ++i;
        } else if (s[i] == '/' && s[i+1] == '*') {
            i += 2;
            while (s[i] != '\0' && s[i+1] != '\0' && (s[i] != '*' || s[i+1] != '/'))
                ++i;
            if (s[i] != '\0' && s[i+1] == '\0')
                ++i;
            if (s[i] == '*')
                i += 2;
        } else if (s[i] == '\"') {
            putchar('\"');
            ++i;
            while (s[i] != '\0' && (s[i-1] == '\\' || s[i] != '\"'))
                putchar(s[i++]);
        } else {
            putchar(s[i++]);
        }
    }
    return 0;
}

Result


Related Tutorials