2012-04-16 107 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