1

「--」と「\cr」の間のテキストを削除したいと思います。

私は実際にファイルから読み込んでいますが、ファイルに「--」が含まれている場合は、「\cr」までのすべてのものとともに「--」を削除する必要があります。

ファイルを1行ずつ読んでいます。

using (StreamReader readFile = new StreamReader(filePath))
{
    string line;

    while ((line = readFile.ReadLine()) != null)
    {
    }
}

部分文字列を使用して文字を探してみました

line.Substring(line.IndexOf("--"),line.IndexOf("\cr"));

しかし、各行の区切り記号を探すのに問題があります

こんなこと書こうと思ってたのに

while ((line = readFile.ReadLine()) != null)
{
    if (line.Substring(line.IndexOf("--")) // If it has "--"
    {
      //Then remove all text from between the 2 delimiters

    }
}

助けてください

ありがとう

編集:

問題は解決しましたが、別の問題に遭遇し/* */ましたが、コメントが複数行にまたがっているため、その間のコメントを削除できません。したがって、 の間のすべてのテキストを削除する必要があります/* */

何か提案や助けはありますか?ありがとう

4

4 に答える 4

1

ファイル内のすべての行からコメントを削除する方法を示すだけです。これは 1 つの方法です。

var newLines = from l in File.ReadAllLines(path)
               let indexComment =  l.IndexOf("--")
               select indexComment == -1 ? l : l.Substring(0, indexComment);
File.WriteAllLines(path, newLines);      // rewrite all changes to the file

編集: との間のすべてを削除したい場合/**/これは可能な実装です:

String[] oldLines = File.ReadAllLines(path);
List<String> newLines = new List<String>(oldLines.Length);
foreach (String unmodifiedLine in oldLines)
{
    String line = unmodifiedLine;
    int indexCommentStart = line.IndexOf("/*");
    int indexComment = line.IndexOf("--");

    while (indexCommentStart != -1 && (indexComment == -1 || indexComment > indexCommentStart))
    {
        int indexCommentEnd = line.IndexOf("*/", indexCommentStart);
        if (indexCommentEnd == -1)
            indexCommentEnd = line.Length - 1;
        else
            indexCommentEnd += "*/".Length;
        line = line.Remove(indexCommentStart, indexCommentEnd - indexCommentStart);
        indexCommentStart = line.IndexOf("/*");
    }

    indexComment = line.IndexOf("--");
    if (indexComment == -1)
        newLines.Add(line);
    else
        newLines.Add(line.Substring(0, indexComment));
}

File.WriteAllLines(path, newLines);
于 2012-05-16T10:48:58.370 に答える
0

コメントを含む行を無視したいようです。どうですか

if (!line.StartsWith("--")) { /* do stuff if it's not a comment */ }

あるいは

if (!line.TrimStart(' ', '\t').StartsWith("--")) { /* do stuff if it's not a comment */ }

行頭の空白を無視します。

于 2012-05-16T10:18:41.127 に答える