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.
- read the text one line at a time.
- find the last occurrence of
//
, if any usingString.LastIndexOf()
- remove the text after (including) the '//' when found
write the line to the output
- ad 1: You can open an TextReader using
System.IO.File.OpenText()
, orFile.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); }
- ad 1: You can open an TextReader using
精彩评论