开发者

How can I delete all the comments in my code?

I'm new to C#, and want to develope a program with which I could delete the comments after // in my code. Is there any simple code recomm开发者_运维技巧ended for this purpose?


It has been suggested that you just search for "//" and trim.

Because you have limited yourself to single-line commands this seems like a relatively simple exercise however it has some tricky cases you need to be thinking about if you intend for the output of the program to be a valid C# application with identical behavior to the input program.

Here are some examples where just searching for "//" and trimming won't work.

Comment in Literal:

string foo = "this is // not a comment";

Comment in Comment

/* you should not trim // this one */

Comment in Comment Part Deux

// This is a comment // so don't just remove this!

Multi-line Comment Adjacency

/* you should not *//* trim this these */

There are certainly other edge cases but these are some low-hanging fruit to think about.


First point, this seems like a bad idea. Comments are useful.

Taking it as an exercise,

Edit: This is a simple solution that will fail on all the case @Bubbafat mentions (and propbably some more). It would still work OK on most source files.

  1. read the text one line at a time.
  2. find the last occurrence of //, if any using String.LastIndexOf()
  3. remove the text after (including) the '//' when found
  4. write the line to the output

    • ad 1: You can open an TextReader using System.IO.File.OpenText(), or File.ReadLines() if you can use Fx4
    • Also open an output file using System.IO.File.WriteText()
    • ad 3: int pos = line.LastIndexOf("//"); if (pos >= 0) { line = line.Substring(0, pos); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜