c# - 仅在评论后删除文本(--)

标签 c# text

我的项目目前正在删除 -- 符号后的所有文本,因为它代表注释。 我的代码现在正在删除文本文件中文本中的所有文本,在评论之前。

到目前为止,这是我的代码:

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/

相关文章:

javascript - kinetic js中的可编辑文本选项

algorithm - 文本打包算法

c# - 绑定(bind)属性不是依赖属性

c# - 为什么不向 Double.MaxValue 添加数字使其成为 Double.PositiveInfinity?

c# - Fluent API 中具有常量的外键

javascript - jquery/javascript 根据日期更改文本颜色

c# - 使用自定义设计器扩展 Visual Studio

c# - LoadViewState 和 SaveViewstate?

jquery - 使用 jQuery 动态更改段落文本?

linux - 从文件中 Grep 文本并打印以上以模式开头的行