advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Rate this item | 0 users have rated this item.
Expertise: Intermediate
Language: Visual Basic
December 16, 2002
Replicate Character Patterns

VB’s String function is useful to fill a large string with a specific character. Occasionally, you might need to fill a string with a repeating set of characters. If you’re using a small database held inside a string, for example, you might want to set default values for some of the fields.

When the need does arise, you can use VB’s Mid statement to handle the task:
 
Dim Data As String
Const Rep = "ABCD"

Data = Rep & Space$(1000)
Mid$(Data, Len(Rep) + 1) = Data

These last two statements do a significant amount of work. The first line allocates the required memory, and the second fills that memory with character data—that’s pretty good for only two lines of code. Not surprisingly, this step is quick, even for large strings, and it provides better functionality than VB’s regular String function:
 
Public Function Replicate (ByVal Number As Long, _
	ByVal Pattern As String) As String
	' Returns PATTERN replicated in a string NUMBER times.
	' Number  = Number of replications desired
	' Pattern = Character pattern to replicate
	Dim LP As Long
	Dim sRet As String
	If Number > 0 Then
		LP = Len(Pattern)
		If LP > 1 Then
			sRet = Pattern & Space$((Number - 1) * LP)
			If Number > 1 Then
				Mid$(sRet, LP + 1) = sRet
			End If
		Else
			sRet = String$(Number, Pattern)
		End If
	End If
	Replicate = sRet
End Function
Larry Serflaten
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs