Piotr Wozniak
Piotr Wozniak

Reputation: 87

Loop over strings added to StringBuilder

I have the following code:

StringBuilder sb = new StringBuilder();
sb.Append("Ola");
sb.Append("Jola");
sb.Append("Zosia");

Can I iterate over StringBuilder object using for, or foreach?

Can I display one element of it? For example Console.WriteLine(sb[0]); doesn't work.

Upvotes: 5

Views: 21006

Answers (6)

Gerhard Diedericks
Gerhard Diedericks

Reputation: 51

I was able to get a workable solution for a very similar scenario by using this post as a guideline:

Replace Line Breaks in a String C#

If you are able to use sb.AppendLine instead you could split the resulting ToString() via the newline characters '\r' and '\n'

// e.g whereas you had:
StringBuilder sb = new StringBuilder();
sb.Append("Ola");
sb.Append("Jola");
sb.Append("Zosia");

// the scenario will only work if you did the following:
StringBuilder sb = new StringBuilder();
sb.AppendLine("Ola");
sb.AppendLine("Jola");
sb.AppendLine("Zosia");

// you can split your strings as follows:
string[] resultLines = TestResultStr.ToString().Split(new char[] { '\n', '\r' });

for (int i = 0; i < resultLines.Length; i++)
{
    Console.WriteLine(resultLines[i]);
}

Upvotes: 0

user9223210
user9223210

Reputation:

I know its too late to answer this question, but i hope someone else get help from this.

 public static void Main(string[] args)
    {

        StringBuilder sb = new StringBuilder("1");
        for(int i=2; i<= 300; i++){
                sb.Append(i+" this is test.~");
        }
        foreach(string s in sb.ToString().Split('~')){
        Console.WriteLine(s);
        }
    }

EDIT: in your example:

 StringBuilder sb = new StringBuilder();
     sb.Append("Ola~");
     sb.Append("Jola~");  
     sb.Append("Zosia~");

 //foreach loop ver sb object

  foreach(string s in sb.ToString().Split('~')){
         Console.WriteLine(s);
          }

Upvotes: 0

CathalMF
CathalMF

Reputation: 10055

If you really want to stick with a StringBuilder you can use an extension method to give you a List and then you can access it with an element number.

internal static class ExtensionMethods
{
    public static List<string> ToList(this StringBuilder stringBuilder)
    {
        return stringBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None).ToList();
    }
}

You can then access it by calling the ToList() method.

int i = 0;
StringBuilder SB = new StringBuilder();
while (i++ != 1000000)
{
    SB.AppendLine(i.ToString());
}

string ChosenElement = SB.ToList()[1000];

Upvotes: 0

w.b
w.b

Reputation: 11228

StringBuilder doesn't implement IEnumerable, so you can't foreach over it, but you can do something like this:

StringBuilder sb = new StringBuilder();
sb.Append("Ola");
sb.Append("Jola");
sb.Append("Zosia");

for (int i = 0; i < sb.Length; i++)
{
    char c = sb[i];
    if (Char.IsUpper(c)) Console.Write('\n');
    Console.Write(c);
}

Upvotes: 3

Fabjan
Fabjan

Reputation: 13676

StringBuilder is not a collection or array. It's just a class that provides some extra features to work with string. It doesn't implement IEnumerable interface.

sb.Append method just concatenates strings like you do if you type "text " + "some other text" but in a much better way in terms of efficiency. In fact every "s1" + "s2" results in creating of new string. If you want to do it like 1000 times so it creates new string again and again with a lot of extra operations to do. StringBuilder provides a way to avoid it, when it 'renders' string it updates the same string instead of creating new istance every time.

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151586

You seem to be looking for a List<string>, to which you can Add() strings that you can later get by index (list[n]) and iterate over (foreach (string s in list)).

StringBuilder doesn't support this, as it concatenates all input internally and can't distinguish between values of different Append() calls afterwards.

To get a concatenated string from a list of strings, see Append List items to StringBuilder.

Upvotes: 4

Related Questions