Search code examples
c#replacecommentswhitespace

Replace every symbol of comments by whitespace


I have some C# code document. Need to replace every symbol of every comment by "whitespace".(need to do this with one-lined and multi-lined comments both).

As example: I have comment: //12345 it must be replaced to 7 whitespaces.

The same with multi-line comments. After doing this action I need to have document with the same symbols count.


@RagtimeWilly, I want something like this:

string testsDocumentTemp = testsDocument;

while (DocumentTemp.Contains("/*"))
{
    int CutFromPosition = DocumentTemp.IndexOf("/*", 0);
    int CutToPosition = DocumentTemp.IndexOf("*/", CutFromPosition) - CutFromPosition;

    string s = testsDocumentTemp.Substring(CutFromPosition, CutToPosition);

    var builder = new StringBuilder();
    builder.Append(' ', s.Length);
    var result = builder.ToString();
    
    DocumentTemp = DocumentTemp.Replace(s, result);
};

while (DocumentTemp.Contains("////"))
{
    int CutFromPosition = DocumentTemp.IndexOf("////", 0);
    int CutToPosition = DocumentTemp.IndexOf("\n", CutFromPosition) - CutFromPosition;

    string s = testsDocumentTemp.Substring(CutFromPosition, CutToPosition);

    var builder = new StringBuilder();
    builder.Append(' ', s.Length);
    var result = builder.ToString();
    
    DocumentTemp = DocumentTemp.Replace(s, result);
};

but much more optimal. (didn't try this code, but I believe it must work). I believe, that this is bad way to resolve the task...


Solution

  • Why do you not want to use regex? Something like this seems like it is perfectly suited to solving the problem:

    public static string ReplaceComments(string input)
    {
        return Regex.Replace(input, @"(/\*[\w\W]*\*/)|//(.*?)\r?\n",
            s => GenerateWhitespace(s.ToString()));
    }
    
    public static string GenerateWhitespace(string input)
    {
        var builder = new StringBuilder();
        builder.Append(' ', input.Length);
    
        return builder.ToString();
    }