Eggins.com
Powershell, .Net, Visual Studio, Team Foundation Server, Windows Communication Foundation

Quick and easy way to measure the length of a string

If you want to quickly measure the length of a string, you can use Powershell. Just enclose the string in quotes and call the Length property.

For example:
    "The quick brown fox jumped over the lazy dog".length
  "C:\Documents and Settings\All Users\Start Menu".length

Even better, if you have copied a multi line string into the clipboard, you can still use powershell to measure the length of that string.

  • Copy your multi line string to the clipboard
  • Open Powershell
  • Type the double quote char to open a string
  • Tap the right mouse button
  • Close the string with the double quote char, and follow that with a ".length"
  01# "123
  >> 456
  >> 789".length
  >>
  11

So this shows that the length of the above string is 11 chars. This is because the string was copied into the Powershell command line, and powershell uses just a line feed character for next-line. If you copied the string from an editor that uses a carriage return and a line feed to mark a new line, then the length reported here will be wrong. I would therefore recommend you do not use the above method. A better method follows.

Lastly, the easiest way of all is to copy your string to the clipboard, open powershell and type:
    {Get-Clipboard).Length

You must enclose Get-Clipboard in the parentheses, as the Get-Clipboard cmdlet does not have a .Length property. The perentheses tells Powershell to execute the Get-ClipBoard function, and then get the value of the "length" property on the returned value (which is a string).

Importantly, you will notice that this function returns 13. This is because the Get-Clipboard returns the actual string in the clipboard, which in my case was a string copied out of Notepad, which uses carriage return and line feed characters to mark the end of each line.


Posted May 31 2007, 10:59 AM by David
Filed under:

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Copyright eggins.com, 1998 - 2008
Powered by Community Server (Non-Commercial Edition), by Telligent Systems