- Preparing Your Machine to Work with Strings
- Working with Strings
- Initializing Strings
- Comparing Strings
- Concatenating Strings
- Finding the String Length
- Comparing and Concatenating Strings in the Sample Application
- Creating Strings from Characters
- Using Escape Characters
- Using Literal Strings
- Accessing the String's Characters
- Finding a Substring within a String
- Extracting Part of the String
- Splitting a String
- Joining a String
- Uppercasing and Lowercasing
- Formatting Strings
- Finishing the Sample Application
- Representing Objects as Strings
- Allocating Strings with StringBuilder
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.
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.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.