LoginSignup
6

More than 5 years have passed since last update.

【VBS】StringBuilder

Posted at

前述

文字列を成形する時、Stirng型の変数に対して下記のような文字列結合式を使いたくない。

aaa
str = str & "追加する文字列"

そこで.NetのStringBuilderを使う。

ソース

StringBuilderテスト
Option Explicit

Dim builder
Set builder = CreateObject("System.Text.StringBuilder")

builder.Append_3 "空にした酒瓶の向こうに見えた怪しげな人影。"
builder.Append_3 "虚ろな光を落とすガス灯の光。"
builder.Append_3 "すべてが快適に淀んだ夜であった。"

WScript.Echo builder.ToString

CreateObjectにより、StringBuilderのオブジェクトを作成する。
C#やVBにてStringBuilderで文字列を追加する際にはAppend()を使うが、ここではAppend_3とする。
少しだけ紹介すると、下記のように与えるパラメタごとにサフィックスが与えられている。
VBScript側でオーバーロードを解決できないからだそうだ。

Append(Char value, Int32 repeatCount)
Append_2(Char[] value, Int32 startIndex, Int32 charCount)
Append_3(String value)
Append_4(String value, Int32 startIndex, Int32 count)
Append_5(Boolean value)
Append_6(SByte value)

...etc

ラッパークラス

個人的にはなるべくC#やVB、Javaで使いなれたStringBuilderの感覚で使いたい。
簡単ながらいくつかメソッドを追加したラッパークラスを作成。

StringBuilder
Class StringBuilder

    ' メンバ
    Dim builder

    ' コンストラクタ
    Private Sub Class_Initialize
        Set builder = CreateObject("System.Text.StringBuilder")
    End Sub

    ' デストラクタ
    Private Sub Class_Terminate
        Set builder = Nothing
    End Sub

    ' 文字列結合
    Public Sub Append(str)
        builder.Append_3 str
    End Sub

    ' 文字列結合(1行追加)
    Public Sub AppendLine(str)
        builder.Append_3 str & vbCrLf
    End Sub

    ' 結合結果削除
    Public Sub Clear()
        Set builder = Nothing
        Set builder = CreateObject("System.Text.StringBuilder")
    End Sub

    ' 結合結果
    Public Function ToString()
        ToString = builder.ToString
    End Function


End Class

追加したメソッドは下記の通り。

  • サフィックスなしのAppend
  • 追加する文字列に改行を加えて追加するAppendLine
  • 結合していった文字列を削除するClear

これでいくらかは普段使うStringBuilderと近い感覚で使えるかな?

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6