2012-05-23 27 views
0

我正在閱讀大多數爲字母字符的文本文件。內容並不真正相關,但每條線的大小非常重要。我將提供此文本的過程將要求每行不超過50個字符。所以我會預處理文本並添加換行符以確保發生。拆分文本文件,以便每行不超過50個字符

我嘗試了幾個像。*。* $的VB.NET正則表達式,但並沒有真正將行分解50個字符。我會拿結果並遍歷每個匹配,然後將其剪切並將其寫入內存中的對象。這可以通過一個正則表達式來完成嗎?

否則,我會使用流讀取器,並在每一行檢查長度,如果< = 50寫出一個Streamwriter。如果> 50將其分割爲50部分,然後使用Streamwriter。

我的文字的一個簡單的例子:

119 SMITH KATY AAAA F ZZZ  X NB SX ET 
      MILES,200/LM450      
120 JONES THOMAS  W QQQ 66-W NB OS SC LW EP  
               ET 
      L/G/B/MAY20-2010/JONES/THOMAS/KEITH  121 BUBBA BILLY HH4 S XQT 2PA-F 1 IP SC LH ET 
               DOCC 
122 NEWTON IAASAC  S FTY 240-U NB QC LF KD EE 

只是尋找有關如何有效地做到這一點提示。

更新:我最終使用了SSS建議的streamreader方法。但是,我試圖避免舊的Mid函數並堅持Substring。因此,我不得不做一些檢查,並使用另一個SO職位的一些代碼,但不記得哪一個。無論如何這裏是:

Dim reader As New StringReader(aSource) 
    Dim line As String = Nothing 
    Dim writer As New StringWriter 
    Dim chunkSize As Integer = 50 
    Dim chunk As String 

    Do 
     line = reader.ReadLine() 
     If Not String.IsNullOrEmpty(line) Then 
      Debug.WriteLine(line.Length & "-->" & line) 
      'if line length is less than or equal to chunk size then write it out, otherwise cut it up and then write the chunks out 
      If line.Length <= chunkSize Then 
       writer.WriteLine(line) 
      Else 
       Debug.WriteLine("---------------------") 
       For i = 0 To line.Length Step chunkSize 
        Debug.WriteLine("i =" & i) 
        Debug.WriteLine("i+c=" & i + chunkSize) 
        Debug.WriteLine("L =" & line.Length) 
        If i + chunkSize > line.Length Then 
         chunk = line.Substring(i, line.Length - i) 
        Else 
         chunk = line.Substring(i, chunkSize) 
        End If 
        Debug.WriteLine(" " & chunk.Length & "-->" & chunk) 
        writer.WriteLine(chunk) 
       Next i 
       Debug.WriteLine("---------------------") 
      End If 
     End If 
    Loop While (line IsNot Nothing) 
    reader.Close() 
    reader.Dispose() 

    'this cut string now becomes our source 
    Debug.WriteLine("==>" & writer.ToString) 
    sourceText = writer.ToString 

    writer.Close() 
    writer.Dispose() 

希望能幫助有同樣問題的人。

+0

是的,我絕對樂觀。這個系統要求每行不超過50個字符,而不管它是否覆蓋。 – sinDizzy

回答

0
Imports System.IO 
Public Class Form1 

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
    Dim strFilenameIn As String = "C:\Junk\Input.TXT" 
    Dim strFilenameOut As String = "C:\Junk\Output.TXT" 
    Try 
     Using sr As New StreamReader(strFilenameIn) 
     Using sw As New StreamWriter(strFilenameOut) 
      Do 
      Dim strLine As String = sr.ReadLine() 
      If strLine Is Nothing Then Exit Do 'EOF 
      For i As Integer = 1 To strLine.Length Step 50 
       sw.WriteLine(Mid(strLine, i, 50)) 
      Next i 
      Loop 
     End Using 
     End Using 
    Catch ex As Exception 
     MsgBox(ex.Message) 
     Exit Sub 
    End Try 
    MsgBox(strfilenameout & " written") 
    End Sub 
End Class 
+0

謝謝。我有一個變化,所以我認爲我在正確的道路上。一旦我調整了它,一些更多的疾病張貼我的例程。 – sinDizzy

相關問題