Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell And StringBuilder

I am new in PowerShell but am familiar with .NET classes.

I am using System.Text.StringBuilder in PowerShell script. The script is that

Function MyStringFunc([String]$line) {     $r = New-Object -TypeName "System.Collections.Generic.List``1[[System.String]]";     $sb = New-Object -TypeName "System.Text.StringBuilder";      foreach ($c in $line) {         $sb.Append($c);         $r.Add($sb.ToString());     }      return $r; }  $line1 = "123"; $a = MyStringFunc $line1; $a 

I expected the result is

1 12 123 

However the result is

                  Capacity                MaxCapacity                    Length                   --------                -----------                    ------                         16                 2147483647                         3 123 

Did I do something wrong?

like image 858
Alex Yeung Avatar asked Oct 18 '11 01:10

Alex Yeung


People also ask

How do I concatenate strings in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator. $str1="My name is vignesh."

Should I use StringBuilder or string?

If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.

What is a string in PowerShell?

The PowerShell string is simply an object with a System. String type. It is a datatype that denotes the sequence of characters, either as a literal constant or some kind of variable. A String can be defined in PowerShell by using the single or double-quotes. Both the strings are created of the same System.

Does C# have StringBuilder?

C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.


1 Answers

Several of the methods on StringBuilder like Append IIRC, return the StringBuilder so you can call more StringBuilder methods. However the way PowerShell works is that it outputs all results (return values in the case of .NET method calls). In this case, cast the result to [void] to ignore the return value e.g.:

[void]$sb.Append($c) 

Note that you don't need to end lines in ; in PowerShell. However if you put multiple commands on the same line then use ;' to separate those commands.

like image 107
Keith Hill Avatar answered Sep 19 '22 19:09

Keith Hill