Manipulating at lines of StringBuilder

  • Thread starter Thread starter BobRoyAce
  • Start date Start date
B

BobRoyAce

1) I have a variable...Dim sb as StringBuilder.
2) I assign a bunch of lines to sb.
3) I can get all the text back as a string with sb.ToString.

My question is how can I programatically update the various lines in
sb? For example, let's say that I want to add 2 spaces to the
beginning of every line in sb. Is there a way to do this easily? I
don't see a way to even read the individual lines in sb, never mind
add text to beginning of each.
 
The big question you need to answer is 'What constitutes a line?'.

Lets just assume for a minute that you have determined a line by appending
an Environment.NewLine to the StringBuilder instance at the point where a
line ends.

In this case you could simply execute:

sb.Insert(0, " ")

sb.Replace(Environment.NewLine, Environment.NewLine & " ")

sb.Remove(sb.Length - 2, 2)

but, in my opinion, a better way could be:

Dim _ss As String() = sb.ToString().Split(New String()
{Environment.NewLine}, None)

sb = New StringBuilder

For Each _s As String In _ss
sb.AppendFormat(" {0}{1}", _s, Environment.NewLine)
Next
 
The big question you need to answer is 'What constitutes a line?'.
Agreed.

Lets just assume for a minute that you have determined a line by appending
an Environment.NewLine to the StringBuilder instance at the point where a
line ends.

That is precisely what I was meaning by a "line".
In this case you could simply execute:

sb.Insert(0, " ")

sb.Replace(Environment.NewLine, Environment.NewLine & " ")

sb.Remove(sb.Length - 2, 2)

but, in my opinion, a better way could be:

Dim _ss As String() = sb.ToString().Split(New String()
{Environment.NewLine}, None)

sb = New StringBuilder

For Each _s As String In _ss
sb.AppendFormat(" {0}{1}", _s, Environment.NewLine)
Next

Thanks for your insights and ideas.
 
1) I have a variable...Dim sb as StringBuilder.
2) I assign a bunch of lines to sb.
3) I can get all the text back as a string with sb.ToString.

My question is how can I programatically update the various lines in
sb? For example, let's say that I want to add 2 spaces to the
beginning of every line in sb. Is there a way to do this easily? I
don't see a way to even read the individual lines in sb, never mind
add text to beginning of each.

If you are doing a lot of modifications you might be better off using
a List(Of String) with each line an entry in the list. That makes
modifying entries very easy. When you are finished you can put the
entries in the list into a StringBuilder.
 
Back
Top