Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

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.24Figure 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.


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

    Figure 4.25Figure 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.

  • + Share This
  • 🔖 Save To Your Account