Login | Register   
LinkedIn
Google+
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: Visual Basic
Expertise: Beginner
Feb 24, 2000

Enhance the Trim Function

The Trim function has a serious shortcoming: It handles only space characters—not all the usual white spaces such as tabs, carriage returns, and line feeds. Instead of the standard Trim function, use my TrimAll function, which handles all white spaces. In fact, you can extend it to trim off any character by editing the assignment to the ToEliminate string variable:
 
Public Function TrimAll(ToTrim As String) As String
	Static ToEliminate As String
	Dim Start As Long, Finish As Long
	' Base condition test
	If Len(ToTrim) = 0 Then
		TrimAll = ""
		Exit Function
	End If
	' Define the characters (once) that we want to trim off
	If Len(ToEliminate) = 0 Then
		ToEliminate = Chr(0) & Chr(8) & Chr(9) _
			& Chr(10) & Chr(13) & Chr(32)
	End If
	' Find the beginning of nonblank string by checking  
	' each char against a list of blank chars.
	Start = 1
	Do While Start <= Len(ToTrim)
		If InStr(ToEliminate, Mid$(ToTrim, Start, 1)) Then
			Start = Start + 1
		Else
			Exit Do
		End If
	Loop
	' Find the end of nonblank string.
	Finish = Len(ToTrim)
	Do While Finish > 1
		If InStr(ToEliminate, Mid$(ToTrim, Finish, 1)) Then
				Finish = Finish - 1
		Else
			Exit Do
		End If
	Loop
	If Start > Finish Then
		' If the string is completely blank,
		' Start will be greater than Finish.
		TrimAll = ""
		Exit Function
	Else
		' Trim out the real contents
		TrimAll = Mid$(ToTrim, Start, Finish - Start + 1)
	End If
End Function
Konstantin Komissarchik
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date