How to remove comments from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void remove_comments(const char *src, char *dest) {
    int i = 0, j = 0;

    while (src[i] != '\0') {

        // Check for // comment
        if (src[i] == '/' && src[i+1] == '/') {
            i += 2;
            while (src[i] != '\n' && src[i] != '\0')
                i++;
        }

        // Check for /* ... */ comment
        else if (src[i] == '/' && src[i+1] == '*') {
            i += 2;
            while (src[i] != '\0' && !(src[i] == '*' && src[i+1] == '/'))
                i++;
            if (src[i] != '\0') i += 2; // skip */
        }

        // Normal character
        else {
            dest[j++] = src[i++];
        }
    }

    dest[j] = '\0';
}

int main() {
    const char *text =
        "int x = 10; // this is a comment\n"
        "int y = 20; /* block comment */\n"
        "int z = x + y; /* multi\n"
        "line\n"
        "comment */ return z;";

    char cleaned[1024] = "";
    remove_comments(text, cleaned);

    printf("%s\n", cleaned);

    return 0;
}



/* 
run:

int x = 10; 
int y = 20; 
int z = x + y;  return z;

*/

 



answered 1 day ago by avibootz
...