advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
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

It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com.
Already a member?





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.
advertisement
advertisement