2012-04-16 56 views
0

我想写一个简单的程序,它需要一个文本文件,将所有字符设置为小写,并删除所有标点符号。我的问题是,当有回车(我相信这就是所谓的)和一个新行,空间被删除。解析文本文件,处理新行?

这是一个
测试句子

变为

这是atestsentence

第一行的最后一个字和下一行的第一个单词被加入。

这是我的代码:

public static void ParseDocument(String FilePath, String title) 
    { 
     StreamReader reader = new StreamReader(FilePath); 
     StreamWriter writer = new StreamWriter("C:/Users/Matt/Documents/"+title+".txt"); 

     int i; 
     char previous=' '; 
     while ((i = reader.Read())>-1) 
     { 
      char c = Convert.ToChar(i); 
      if (Char.IsLetter(c) | ((c==' ') & reader.Peek()!=' ') | ((c==' ') & (previous!=' '))) 
      { 
       c = Char.ToLower(c); 
       writer.Write(c);      
      } 
      previous = c; 

     } 

     reader.Close(); 
     writer.Close(); 
    } 

这是一个简单的问题,但我想不出检查新行插入空间的方式。任何帮助是极大的赞赏。

+1

一个文本文件,你想换行保持不动,是吗?在这种情况下,不要只检查字母;检查回车和换行。 – 2012-04-16 16:35:57

+1

关于在Reader和Writer中使用'using()'的强制性注释。 – 2012-04-16 16:40:15

回答

2

取决于一点上,你要如何对待空行,但是这可能工作:

char c = Convert.ToChar(i); 

if (c == '\n') 
    c = ' ';  // pretend \n == ' ' and keep ignoring \r 

if (Char.IsLetter(c) | ((c==' ') & reader.Peek()!=' ') | ((c==' ') & (previous!=' '))) 
{ 
    ... 

我希望这是一个锻炼,在正常的做法,你会读与System.IO.File.ReadAllLines()System.IO.File.ReadLines()

+0

谢谢,这就是我一直在寻找! – Matt 2012-04-16 16:42:03

0

尝试

myString.Replace(Environment.NewLine, “替换文本”)

Replace Line Breaks in a String C#

+1

没有myString,OP一次读取1个字符。 – 2012-04-16 16:35:28

+0

ups,那么可能你的方式是正确的。 – elrado 2012-04-16 16:37:47