Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB
Expertise: Intermediate
Dec 27, 2006

Clear All Occurences of Extra White Space

This function clears all occurences of extra white space (spaces, tabs, blank lines) and programming comments beginning with ';' in a file and saves the cleaned file as another file.

It uses the following I/P arguments:

  • The inbuilt Ltrim and Rtrim functions can remove spaces only on the sides but not internal ones. This function can also remove the extra internal spaces.
  • Filepath of the file to be cleaned
  • Filepath of the cleaned file to be saved
You can use the Loop and Replace function to find all adjacent spaces " " and replace them with single spaces " ". Keep doing this until the entire string becomes proper.

'Sub for clearing WhiteSpaces
Sub ClearSpace(withSpace As String, withoutSpace As String)

If withSpace = withoutSpace Then
  MsgBox "Both Files Same", vbCritical, "Error:"
  Exit Sub
End If

Dim fs As Object
Dim tmpWhiteSpace As Object
Dim tmpFile As Object
Dim var_txt As String
Dim pos As Long

Set fs = CreateObject("Scripting.FileSystemObject")
Set tmpWhiteSpace = fs.OpenTextFile(withSpace, 1)
Set tmpFile = fs.CreateTextFile(withoutSpace, True)

Do While (Not tmpWhiteSpace.AtEndOfStream)
  var_txt = tmpWhiteSpace.readLine
  
  'Remove comments that begin with ';'
  pos = InStr(1, var_txt, ";", vbTextCompare)
  If pos <> 0 Then
     var_txt = Left(var_txt, pos - 1)
  End If
  
  'Remove Internal Extra White Spaces
  While var_txt <> Replace(var_txt, "  ", " ", 1, -1, vbTextCompare)
    var_txt = Replace(var_txt, "  ", " ", 1, -1, vbTextCompare)
  Wend

  'For removing all the spaces at the ends
  var_txt = LTrim(RTrim(var_txt)) 
  If (var_txt <> "") Then
     tmpFile.WriteLine var_txt
  End If
Loop

tmpWhiteSpace.Close
tmpFile.Close 'Closes and Saves the contents
End Sub
Sameer Palande
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap