1

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

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

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 谢谢

4

3 回答 3

2

您可以使用正则表达式或以下代码

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
}

如果评论在下面的布局中

等等等等——一些评论——更多评论

阿达斯达斯法

asasff——更多评论

于 2012-05-16T12:49:54.753 回答
2

s.indexOF 搜索第一次使用“--” s.remove 从 indexof 开始并删除所有内容到最后。 编辑: 根据 Jays 评论修复异常

        string s = "aa--aa";
        int i = s.IndexOf("--");
        if (i >= 0)
            s = s.Remove(i);
        MessageBox.Show(s);

或者在这里我为你划了一个

        string s = "aa--aa";
        s = s.IndexOf("--") >= 0 ? s.Remove(s.IndexOf("--")) : s;
于 2012-05-16T12:53:50.093 回答
1

您的代码中的问题是,仅当文件包含与“--”完全相同的行时,才会发生替换(这是写入输出文件的唯一指令)。

此外,如果您使用的是 WriteAllText 和 ReadAllText,则不需要 while 循环,并且无论如何您都不能使用它们,因为这样您只会删除“--”而不是之后的所有内容。

我认为这样的事情应该有效:

using (StreamReader reader = new StreamReader( text ))
{
    using (StreamWriter writer = new StreamWriter( file ))
    {
        while (( line = reader.ReadLine() ) != null)
        {
            int idx = line.IndexOf(line_to_delete);
            if (idx == 0) // just skip the whole line
                continue;
            if (idx > 0)
                writer.WriteLine(line.Substring(0, idx));
            else
                writer.WriteLine(line);
        }
    }
}
于 2012-05-16T13:17:55.123 回答