Manipulating Strings in C#—Finding the String Length

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Manipulating Strings in C#

© 2003 Peachpit Press

Finding the String Length

There are times when it's important to find out the length of a string. Usually developers want to know if the string variable has been initialized, and, if it has been initialized, if the length of the string is greater than zero.

To find the length of a string:

  • Use the Length property of the string class. Since Length is a property, you don't put parenthesis after the property name (Figure 4.24).


Image:CSharpWebDevASPNET4-24.gif
Figure 4.24 The nice thing about having a framework that every language uses is that you use the same command, Length, to get the size of the string in every language.

Tips

  • A string variable that has not been initialized doesn't have a length—its length isn't zero. If you try to ask for the Length of a null variable you will get an error. However, if you initialize the variable to " " then its length will be zero (Figure 4.25).


Image:CSharpWebDevASPNET4-25.gif
Figure 4.25 This is exactly the reason you should check for null before calling a method in string. In this case if you call Length before the string has been initialized you will get a runtime exception.


Previous_Page_.gif Next_Page_.gif


Personal tools