aku1 发表于 2007-12-20 14:00:08 |
Many times you want to work with only a portion of a string value. For example, Windows Script Host (WSH) has a property, FullName, which tells you whether a script is running under CScript or WScript. This can be useful information because you are likely to have certain scripts that should be, or in some cases can only be, run under CScript. However, the FullName property returns not just the name of the script host but the full path to the script host executable file. Typically these paths are: C:\Windows\Cscript.exe
C:\Windows\Wscript.exe.
Of course, most of the time you are not interested in the full path but only the name of the script host; after all, the full path will vary depending on the drive and the directory where Windows is installed. Because of this, you need a method for retrieving only the last eight characters (cscript.exe or wscript.exe) of the path string.
At other times, the length of a string is very important. This is particularly true when it comes to formatting output either to display in a command window or to save to a text file. For example, the following script retrieves a collection of files stored in C:\Windows and displays the file name, file size, and last access time for each one: Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder("C:\Windows")
Set FileList = Folder.Files
For Each File in FileList
Wscript.Echo File.Name & VbTab & File.Size & File.DateLastModified
Next
When the preceding script runs, output similar to the following appears. As you can see, it is very difficult to make immediate sense of this output. PCL5EMS.X12 46618/3/00 9:07:50 AM
SchedLog.Txt 1778412/17/00 7:51:40 PM
Straw Mat.bmp 5905/11/98 8:01:00 PM
Bubbles.bmp 21185/11/98 8:01:00 PM
Carved Stone.bmp 5825/11/98 8:01:00 PM
HKLM 3711/12/99 8:27:20 AM
LT Win Modem.log 207512/3/01 9:30:16 PM
When placed in tabular format, with well-defined columns, the data is much easier to read and to analyze: PCL5EMS.X12 4661 8/3/00 9:07:50 AM
SchedLog.Txt 17784 12/17/00 7:51:40 PM
Straw Mat.bmp 590 5/11/98 8:01:00 PM
Bubbles.bmp 2118 5/11/98 8:01:00 PM
Carved Stone.bmp 582 5/11/98 8:01:00 PM
HKLM 371 1/12/99 8:27:20 AM
LT Win Modem.log 2075 12/3/01 9:30:16 PM
To create tabular output such as this, you need to be able to take string values and manipulate them in various ways. For example, in the preceding output, the file name begins in the first character position, and the file size begins in the 51st character position (digits have been added to make it easier to identify character positions): 123456789012345678901234567890123456789012345678901
PCL5EMS.X12 4661 8/3/00 9:07:50 AM
To create this output, you need to:
1. |
Calculate the length of the file name. (For example, PCL5EMS.X12 is 11 characters long.) |
2. |
Subtract the length of the file name (11 characters) from the total space allocated for the file name (50 characters). |
3. |
Append enough blank spaces (50 minus 11, or 39 blank spaces) to ensure that the length of the file name equals the total space allocated. |
This works very well for short file names. But what if you had a file name of 75 characters? In that case, you would need to truncate the string, taking only the first 50 characters and leaving off the rest.
Fortunately, VBScript includes a number of functions that allow you to manipulate strings. For example, you can calculate the length of a string and add blank spaces to pad the length, or use functions that return only a specified number of characters, beginning either from the start of the string and working forward or from the end of the string and working back (or even from some point in the middle and working in either direction).
Some of the more commonly used functions for manipulating strings are shown in Table 2.14.
Table 2.14 String Manipulation Functions
Len |
Returns the number of characters in a string. This is particularly useful when formatting data for on-screen display. Suppose you allow 20 characters for a particular column. To ensure that columns line up correctly, you need to determine the number of characters in the string and then add or subtract characters as needed until the string is 20 characters long.
The following two lines of code returns the value 22 because 22 characters are in the string This is a test string. TestString = "This is a test string."
Wscript.Echo Len(TestString)
|
Left |
Returns the specified number of characters from the string, starting with the first character and working forward toward the end of the string (from left to right). You must supply two parameters: the string and the number of characters to return.
The following two lines of code return the string Thi because these are the first three characters in the string This is a test string. TestString = "This is a test string."
Wscript.Echo Left(TestString, 3)
|
Right |
Returns the specified number of characters from the string, starting with the last character and working backward toward the beginning of the string (from right to left). You must supply two parameters: the string and the number of characters to return.
The following two lines of code return the string ng. because these are the last three characters in the string This is a test string. TestString = "This is a test string."
Wscript.Echo Right(TestString, 3)
|
Mid |
Returns the specified number of characters from the string, starting with a designated character position and working toward the end of the string (from left to right). You must supply three parameters: the string, the starting character position (for example, 5 to start counting from the fifth character in the string), and the number of characters to return.
The following two lines of code return the string is_ (with the underscore representing a blank space) because these are the characters that hold positions 6, 7, and 8 in the string This is a test string. TestString = "This is a test string."
Wscript.Echo Mid(TestString, 6, 3)
|
Space |
Inserts the specified number of blank spaces into a string. For example, the following line of code inserts 10 blank spaces between "This is a" and "test string." The end result is the string "This is a test string."Wscript.Echo "This is a" & Space(10) _ & "test string." Wscript.Echo "This is a" & Space(10) _
& "test string."
|
LTrim |
Removes any blank spaces that appear at the beginning of a string. (These are typically referred to as leading spaces.) For example, the following code transforms the string " This is a test string. " into "This is a test string. "TestString = " This is a test string. " Wscript.Echo LTrim(TestString) TestString = " This is a test string. "
Wscript.Echo LTrim(TestString)
|
RTrim |
Removes any blank spaces that appear at the end of a string. (These are typically referred to as trailing spaces.) For example, the following code transforms the string " This is a test string. " into " This is a test string."TestString = " This is a test string. " Wscript.Echo RTrim(TestString) TestString = " This is a test string. "
Wscript.Echo RTrim(TestString)
|
Trim |
Removes both the leading and trailing spaces from a string. For example, the following code transforms the string " This is a test string. " into "This is a test string."TestString = " This is a test string. " Wscript.Echo Trim(TestString) TestString = " This is a test string. "
Wscript.Echo Trim(TestString)
|
Creating Tabular Output
The string manipulation functions are particularly useful in creating tabular output, output in which items are displayed in aligned columns. An example of this is shown in the following script, which uses the Len and Space functions to create a table showing two services and their current state. The script in Listing 2.18 does the following:
1. |
Sets the value of four variables, two representing the names of services and two representing service states. |
2. |
For the first service variable, uses the Len function to determine the number of characters in the string and saves this value to the variable NameLength. For example, Alerter has seven characters in its name, so the value 7 is saved to NameLength. |
3. |
Subtracts the value of NameLength from 20, the number of spaces allocated for displaying the service name, and stores the difference in the variable SpacesToAdd. For the Alerter service, this value would be 13: 20 - 7. |
4. |
Sets the value of the variable DisplayName to the name of the service plus as many blank spaces as needed to make the name 20 characters long. For example, the Alerter service requires 13 blank spaces (the value stored in SpacesToAdd) to make the name 20 characters long. These blank spaces are added using the Space function.
The DisplayName for the Alerter service looks like this (the hyphens indicate blank spaces): Alerter-------------
|
5. |
Echoes the DisplayName and the service state. |
6. |
Repeats the process for the next two variables. |
Listing 2.18 Creating Tabular Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Service1 = "Alerter"
State1 = "Running"
Service2 = "DHCP Client"
State2 = "Stopped"
NameLength = Len(Service1)
SpacesToAdd = 20 - NameLength
DisplayName = Service1 & Space(SpacesToAdd)
Wscript.Echo DisplayName & State1
Display = ""
NameLength = Len(Service2)
SpacesToAdd = 20 - NameLength
DisplayName = Service2 & Space(SpacesToAdd)
Wscript.Echo DisplayName & State2
|
When this script runs under CScript, the following output appears in the command window: Alerter Running
DHCP Client Stopped
Formatting Text for Message Boxes
If you prefer using message boxes to display data, you will discover that it is much harder, if not impossible, to display data in aligned columns. This is because of a difference in the fonts used in a command window and the fonts used in a message box. The command window uses a nonproportional font, which means that all characters (including spaces) are the same width. As shown in Figure 2.14, the letters i, j, and l take up the same amount of space as the letters m, v, and w in a nonproportional font.
Figure 2.14 Letters Displayed in Nonproportional Font
By contrast, message boxes typically use a proportional font, which means that characters vary in width. As shown in Figure 2.15, the letters i, j, and l take up far less space than the letters m, v, and w in a proportional font.
Figure 2.15 Letters Displayed in Proportional Font
Because of the differences in character widths, you cannot specify that a column should begin at, say, the 20th character space, and assume that all the column items will line up.
Table 2.15 Functions for Modifying String Case
LCase |
Converts all the alphabetic characters in a string to their lowercase equivalents.
The following lines of code convert the string Arlene Huff to the all-lowercase string arlene huff. UserName = "Arlene Huff"
Wscript.Echo LCase(UserName)
|
UCase |
Converts all the alphabetic characters in a string to their uppercase equivalents.
The following lines of code convert the string Arlene Huff to the all-uppercase string ARLENE HUFF. UserName = "Arlene Huff" Wscript.Echo UCase(UserName |
|