我的项目目前正在删除 -- 符号后的所有文本,因为它代表注释。 我的代码现在正在删除文本文件中文本中的所有文本,在评论之前。
到目前为止,这是我的代码:
static void Main( string[] args )
{
string line = null;
string line_to_delete = "--";
string desktopLocation = Environment.GetFolderPath( Environment.SpecialFolder.Desktop );
string text = Path.Combine( desktopLocation, "tim3.txt" );
string file = Path.Combine( desktopLocation, "tim4.txt" );
using (StreamReader reader = new StreamReader( text ))
{
using (StreamWriter writer = new StreamWriter( file ))
{
while (( line = reader.ReadLine() ) != null)
{
if (string.Compare( line, line_to_delete ) == 0)
File.WriteAllText( file, File.ReadAllText( text ).Replace( line_to_delete, "" ) );
continue;
}
}
我如何指定它必须只删除 te 谢谢
最佳答案
您可以使用 RegEx 或以下代码
var @index = line.IndexOf(line_to_delete);
if(@index != -1){
var commentSubstring = line.Substring(@index, line.Length - @index); //Contains only the comments
line.Replace(commentSubstring, "").ToString()//Contains the original with no comments
}
如果评论在下面的布局中
Blah blah -- 一些评论 --更多评论
阿达斯达斯 阿斯法斯法
asasff --更多评论
关于c# - 仅在评论后删除文本(--),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618841/