0

I'm trying to append text to a large amount of strings (in the thousands), and also do some other string manipulations.

However, I have about 60 lines of if/else and string appending and it takes several minutes to go through so many lines of text.

It does several checks, but the main part of it uses:

newstring += appendText.Text + ' ' + inputTextBox.Lines[i];

Is there a better way to do this that makes it faster?

1

You are thinking correctly, appending text using plus operator is not optimal. Use StringBuilder for this, especially if conditionals are used:

(code from link above)

StringBuilder sb = new StringBuilder();

sb.Append("This is a sentence.");

for (int ctr = 0; ctr <= 10; ctr++) {
    sb.Append("This is an additional sentence.");             
}   

Than call sb.ToString(); to show full string.

Note: There are at least 6 ways to concatenate a string in c# (all examples produce "a b"):

Usually, if you use .net 4.6 you will want to use string interpolation for shorter ones, and StringBuilder for longer. Prior to .net 4.6 insted of interpolation, use string.Format().

Not the answer you're looking for? Browse other questions tagged or ask your own question.