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 ).

    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.
     string str="this is a very long string. Don't you think?"; Response.Write(  str.Length  ); //prints out: 44 

graphics/tick.gif Tip

  • A string variable that has not been initialized doesn't have a lengthits 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 ).

    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.
     string str; //  error  str has not been initialized //str is currently null if (str.Length > 0)   Response.Write(str); str = ""; //  no error  but length is zero //so the if is not executed if (str.Length > 0)   Response.Write(str); 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net