StringBuilder

0

VBA

목록 보기
8/13

베이직언어의 나름 강점중 하나는 문자열처리인데, 사실 이건 과거의 영광이다. 베이직의 라떼시절에는 타언어와 비교하여 편리하고 강력했다.

mscorlib 타입라이브러리에는 ArrayList외에 몇 가지 사용가능한 개체가 있는 데, 그중 'StringBuilder'라는 게 있다. 이를 이용하여 문자열이 단순한 데이터타입이 아니라 개체가 되어 메서드를 가진다는, 이젠 당연한 것 같은 일을 할 수 있다.

다음은 몇 가지 예인데, 사실 굳이 이걸 사용할 것 같진 않다. 익숙한 구닥다리 문법이 아직은 편하기 때문이다.

Dim s As Object
Dim value As Long

Set s = CreateObject("System.Text.StringBuilder")
s.Append_3 "The quick brown fox jumped over the lazy dog. "
s.Append_3 "Mary had a little lamb."
Debug.Print s.length, s.Capacity
Debug.Print s.ToString

s.Replace "quick", "slow"
Debug.Print s.ToString

value = 4
s.Insert_2 value, "very very "
Debug.Print s.ToString
Set s = Nothing

mscorlib 타입라이브러리 말고 별도로 StringBuilder를 VBA에서 흉내를 내어본 클래스모듈이 있는데(내가 만든 건 아니다), 소개하자면 다음과 같다.

' Class: StringBuilder

Option Explicit

Private Const initialLength As Long = 32

Private totalLength As Long  ' Length of the buffer
Private curLength As Long    ' Length of the string value within the buffer
Private buffer As String     ' The buffer

Private Sub Class_Initialize()
  ' We set the buffer up to it's initial size and the string value ""
  totalLength = initialLength
  buffer = Space(totalLength)
  curLength = 0
End Sub

Public Sub Append(Text As String)

  Dim incLen As Long ' The length that the value will be increased by
  Dim newLen As Long ' The length of the value after being appended
  incLen = Len(Text)
  newLen = curLength + incLen

  ' Will the new value fit in the remaining free space within the current buffer
  If newLen <= totalLength Then
    ' Buffer has room so just insert the new value
    Mid(buffer, curLength + 1, incLen) = Text
  Else
    ' Buffer does not have enough room so
    ' first calculate the new buffer size by doubling until its big enough
    ' then build the new buffer
    While totalLength < newLen
      totalLength = totalLength + totalLength
    Wend
    buffer = Left(buffer, curLength) & Text & Space(totalLength - newLen)
  End If
  curLength = newLen
End Sub

Public Property Get Length() As Integer
  Length = curLength
End Property

Public Property Get Text() As String
  Text = Left(buffer, curLength)
End Property

Public Sub Clear()
  totalLength = initialLength
  buffer = Space(totalLength)
  curLength = 0
End Sub

'//// 사용법은 다음과 같다;
Sub demoStringBuilder()
  Dim i As Long
  Dim sb As StringBuilder
  Dim result As String
  
  Set sb = New StringBuilder
  
  For i = 1 To 10
    sb.Append CStr(i)
  Next
  
  result = sb.Text
  Debug.Print result
End Sub
profile
harmonized or torn between programming and finance

0개의 댓글