0

嗨,我正在尝试通过文件 grep 并计算行数、每行的最大空格数和最长的行。

如果我通过给定文件的字符槽迭代字符,我如何确定“/ n”字符?

非常感谢。

这是我用于此的代码:

    using (StreamReader sr = new StreamReader(p_FileName))
     {

  char currentChar;
  int current_length=0,current_MaximumSpaces=0;
    p_LongestLine=0;
    p_NumOfLines=0;
    p_MaximumSpaces=0;
    while (!sr.EndOfStream){
        currentChar=Convert.ToChar(sr.Read());
        current_length++;
        if(Char.IsWhiteSpace(currentChar) || currentChar==null){
            current_MaximumSpaces++;
        }
        if(currentChar == '\n'){
            p_NumOfLines++;
        }
        if(current_length>p_LongestLine){
            p_LongestLine=current_length;
        }
        if(current_MaximumSpaces>p_MaximumSpaces){
            p_MaximumSpaces=current_MaximumSpaces;
        }
        current_length=0;
        current_MaximumSpaces=0;
    }
    sr.Close();
}
4

3 回答 3

5
if(currentChar == '\n')
    count++;
于 2012-04-12T13:22:36.630 回答
2

您不需要逐个字符:为了您的目的,逐行进行就足够了,并且您可以让 .NET 为您处理与系统相关的换行符作为额外的奖励。

int maxLen = -1, maxSpaces = -1;
foreach ( var line in File.ReadLines("c:\\data\\myfile.txt")) {
    maxLen = Math.Max(maxLen, line.Length);
    maxSpaces = Math.Max(maxSpaces, line.Count(c => c == ' '));
}

编辑:您的程序不起作用,因为与您检查无关的错误'\n':您将每个字符后的current_lengthand清零current_MaximumSpaces,而不是仅在看到换行符时才清除它们。

于 2012-04-12T13:39:46.513 回答
0

尝试比较Environment.NewLine

bool is_newline = currentChar.ToString().Equals(Environment.NewLine);

我猜你换行实际上是\r\n(非Unix)结束。您需要跟踪前一个/当前字符并查找\r\nEnvironment.NewLine

于 2012-04-12T13:28:34.210 回答