How to remove comments from a string in C#

2 Answers

0 votes
// Remove both // and /* ... */ comments 

using System;
using System.Text;

class Program
{
    static string RemoveComments(string input) {
        StringBuilder output = new StringBuilder();
        int i = 0;

        while (i < input.Length) {
            // Check for // comment
            if (i + 1 < input.Length && input[i] == '/' && input[i + 1] == '/') {
                i += 2;
                while (i < input.Length && input[i] != '\n')
                    i++;
            }
            // Check for /* ... */ comment
            else if (i + 1 < input.Length && input[i] == '/' && input[i + 1] == '*') {
                i += 2;
                while (i + 1 < input.Length && !(input[i] == '*' && input[i + 1] == '/'))
                    i++;
                if (i + 1 < input.Length) i += 2;
            }
            else {
                output.Append(input[i]);
                i++;
            }
        }

        return output.ToString();
    }

    static void Main()
    {
        string text =
@"int x = 10; // single-line comment
int y = 20; /* block comment */
int z = x + y; /* multi
line
comment */ return z;";

        string cleaned = RemoveComments(text);

        Console.WriteLine(cleaned);
    }
}


/* 
run:

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

*/

 



answered May 1 by avibootz
0 votes
// Remove only // comments

using System;

class Program
{
    static string RemoveSingleLineComments(string input) {
        var lines = input.Split('\n');
        for (int i = 0; i < lines.Length; i++) {
            int pos = lines[i].IndexOf("//");
            if (pos >= 0)
                lines[i] = lines[i].Substring(0, pos);
        }
        
        return string.Join("\n", lines);
    }

    static void Main()
    {
        string text =
@"int a = 5; // comment
int b = 6; // another";

        Console.WriteLine(RemoveSingleLineComments(text));
    }
}



/* 
run:

int a = 5; 
int b = 6; 

*/

 



answered May 1 by avibootz
...