Chapter 14. Working with Strings

Previous lessons provided a sneak peek at some of the things that a Visual Basic program can do with strings. Lesson 11 explained how you can use the & operator to concatenate two strings. Several lessons show how to use the ToString method to convert numeric values into strings that you can then display to the user.

In this lesson, you learn a lot more about strings. You learn about String class methods that let you search strings, replace parts of strings, and extract pieces of strings. You also learn new ways to format numeric and other kinds of data to produce strings.

STRING METHODS

The String class provides a lot of useful methods for manipulating strings. For example, the EndsWith method returns True if a string ends with a particular substring. The following code determines whether a string ends with the substring dog:

Dim str As String = "The quick brown fox jumps over the lazy dog"
MessageBox.Show("Ends with dog: " & str.EndsWith("dog"))

Table 14-1 summarizes the String class's most useful methods.

Table 14.1. TABLE 14-1

METHOD

PURPOSE

Contains

Returns True if the string contains a target string.

EndsWith

Returns True if the string ends with a target string.

IndexOf

Returns the index of a target character or string within the string.

IndexOfAny

Returns the index of the first occurrence of any of a set of characters in the string.

Insert

Inserts text in the middle of the string.

LastIndexOf

Returns the index of the last occurrence of a target character or string within the string.

LastIndexOfAny

Returns the index of the last occurrence of any of a set of characters in the string.

PadLeft

Pads the string to a given length by adding characters on the left if necessary.

PadRight

Pads the string to a given length by adding characters on the right if necessary.

Remove

Removes a piece of the string.

Replace

Replaces occurrences of a string or character with new values within the string.

Split

Splits the string apart at a delimiter (for example, commas) and returns an array containing the pieces.

StartsWith

Returns True if the string starts with a target string.

Substring

Returns a substring.

ToLower

Returns the string converted to lowercase.

ToUpper

Returns the string converted to uppercase.

Trim

Removes leading and trailing characters from the string. A version that takes no parameters removes whitespace characters (space, tab, newline, and so on).

TrimEnd

Removes trailing characters from the string.

TrimStart

Removes leading characters from the string.

Note

Remember that string indexing starts with 0 so the first letter has index 0, the second has index 1, and so forth.

In addition to all of these methods, the String class provides a very useful Length property. As you can probably guess, Length returns the number of characters in the string.

The String class also provides the useful shared methods Format and Join. A shared method is one that is provided by the class itself rather than an instance of the class. You invoke a static method using the class's name instead of a variable's name.

The Format method formats a series of parameters according to a format string and returns a new string. For example, the following code uses the String class's Format method to display the values in the variables x and y surrounded by parentheses and separated by a comma:

Dim x As Integer = 10
Dim y As Integer = 20
Dim txt As String = String.Format("({0}, {1})", x, y)
MessageBox.Show(txt)

The next section says more about the Format method.

The Join method does the opposite of the Split method: it joins a series of strings, separating them with a delimiter.

FORMAT AND TOSTRING

The String class's Format method builds a formatted String. Its first parameter is a format string that tells how the method should display its other parameters. The format string can contain literal characters that are displayed as they appear, plus formatting fields.

Each field has the following syntax:

{index[,alignment][:formatString]}

The curly braces are required. The square brackets indicate optional pieces.

The key pieces of the field are:

  • index — The zero-based index of the Format method's parameters that should be displayed by this field.

  • alignment — The minimum number of characters that the field should use. If this is negative, the field is left-justified.

  • formatString — The format string that indicates how the field's value should be formatted. The following format sections describe some of the many values that you can use here in addition to literal characters.

For example, the following code defines a String and two Decimal values. It then displays the result in a message box.

Dim itemName As String = "Fiendishly Difficult Puzzles"
Dim quantity As Decimal = 2D
Dim price_each As Decimal = 9.99D

MessageBox.Show(
    String.Format("You just bought {1} {0} at {2:C} each.",
    itemName, quantity, price_each))

The format string is "You just bought {1} {0} at {2:C} each."

The first field is {1}. This displays parameter number 1 (the second parameter — remember they're zero-based).

The second field is {0}. This displays the first parameter.

The third field is {2:C}. This displays the third parameter with the format string C, which formats the value as currency.

The result is:

You just bought 2 Fiendishly Difficult Puzzles at $9.99 each.

The following code shows an example that uses field widths to make values line up in columns. Before the code executes, assume that itemName1, quantity1, and the other variables have already been initialized. (The Console.WriteLine statement writes output into the Output window.)

Console.WriteLine(
    String.Format("{0,-20}{1,5}{2,10}{3,10}",
    "Item", "Qty", "Each", "Total")
)
Console.WriteLine(
    String.Format("{0,-20}{1,5}{2,10:C}{3,10:C}",
    itemName1, quantity1, priceEach1, quantity1 * priceEach1)
)
Console.WriteLine(
    String.Format("{0,-20}{1,5}{2,10:C}{3,10:C}",
    itemName2, quantity2, priceEach2, quantity2 * priceEach2)
)
Console.WriteLine(
    String.Format("{0,-20}{1,5}{2,10:C}{3,10:C}",
    itemName3, quantity3, priceEach3, quantity3 * priceEach3)
)

Notice that the code begins with a line that defines the column headers. Its formatting string uses the same indexes and alignment values as the other formatting strings so the headers line up with the values below.

The following shows the result:

Item                  Qty      Each     Total
Pretzels (dozen)        4     $5.95    $23.80
Blue laser pointer      1   $149.99   $149.99
Titanium spork          2     $8.99    $17.98

Note

Because the format string is just a string, you could define it in a constant or variable and then use that variable as the first argument to the Format method. That way you are certain that all of the Format statements use the same string. This also makes it easier to change the format later if necessary.

Every object provides a ToString method that converts the object into a string. For simple data types such as numbers and dates, the result is the value in an easy-to-read string.

The ToString method for some objects can take a format parameter that tells how you want the item formatted. For example, the following statement displays the variable cost formatted as a currency value in the Output window:

Console.WriteLine(cost.ToString("C"))

The following sections describe standard and custom format strings for numbers, dates, and times. You can use these as arguments to the ToString method or as format strings passed to String.Format.

Standard Numeric Formats

Formatting characters tell String.Format and ToString how to format a value. For the characters discussed in this section, you can use either an uppercase or lowercase letter. For example, you can use C or c for the currency format.

Table 14-2 summarizes the standard numeric formatting characters.

Table 14.2. TABLE 14-2

CHARACTER

MEANING

EXAMPLE

C

Currency with a currency symbol, thousands separators, and a decimal point.

$12,345.67

D

Decimal. Integer types only.

12345

E

Scientific notation.

1.234567E+004

F

Fixed-point.

12345.670

G

General. Either fixed-point or scientific notation, whichever is shorter.

12345.67

N

Similar to currency except without the currency symbol.

12,345.67

P

Percent. The number is multiplied by 100 and a percent sign is added appropriately for the computer's locale. Includes thousands separators and a decimal point.

123.45 %

R

Round trip. The number (double or float only) is formatted in a way that guarantees it can be parsed back into its original value.

1234.567

X

Hexadecimal.

3A7

You can follow several of these characters with a precision specifier that affects how the value is formatted. How this value works depends on the format character that it follows.

For the D and X formats, the result is padded on the left with zeros to have the length given by the precision specifier. For example, the format D10 produces a decimal value padded with zeros to 10 characters.

For the C, E, F, N, and P formats, the precision specifier indicates the number of digits after the decimal point.

Custom Numeric Formats

If the standard numeric formatting characters don't do what you want, you can use a custom numeric format. Table 14-3 summarizes the custom numeric formatting characters.

Table 14.3. TABLE 14-3

CHARACTER

MEANING

0

Digit or zero. A digit is displayed here or a zero if there is no corresponding digit in the value being formatted.

#

Digit or nothing. A digit is displayed here or nothing if there is no corresponding digit in the value being formatted.

.

Decimal separator. The decimal separator goes here. Note that the actual separator character may not be a period depending on the computer's regional settings, although you still use the period in the format string.

,

Thousands separator. The thousands separator goes here. The actual separator character may not be a comma depending on the computer's regional settings, although you still use the comma in the format string.

%

Percent. The number is multiplied by 100 and the percent sign is added at this point. For example, %0 puts the percent sign before the number and 0% puts it after.

E+0

Scientific notation. The number of 0s indicates the number of digits in the exponent. If + is included, the exponent always includes a + or – sign. If + is omitted, the exponent only includes a sign if the exponent is negative. For example, the format string #.##E+000 used with the value 1234.56 produces the result 1.23E+003.

Escape character. Whatever follows the is displayed without any conversion. For example, the format 0.00\% would add a percent sign to a number without scaling it by 100 as the format 0.00% does.

'ABC'

Literal string. Characters enclosed in single quotes are displayed without any conversion.

;

Section separator. See the following text.

You can use a section separator to divide a formatting string into two or three sections. If you use two sections, the first applies to values greater than or equal to zero, and the second section applies to values less than zero. If you use three sections, they apply to values that are greater than, less than, and equal to zero, respectively.

For example, Table 14-4 shows the result produced by the three-section custom formatting string "{0:$#,##0.00;($#,##0.00); -- zero -- }" for different values.

Table 14.4. TABLE 14-4

VALUE

FORMATTED RESULT

12345.678

$12,345.68

−12345.678

($12,345.68)

0.000

— zero —

Standard Date and Time Formats

Just as numeric values have standard and custom formatting strings, so too do dates and times.

Table 14-5 summarizes the standard date and time formatting patterns. The examples are those produced for 1:23 PM August 20, 2011 on my computer set up for US English. Your results will depend on how your computer is configured. Note that for many of the characters in this table, the uppercase and lowercase versions have different meanings.

Table 14.5. TABLE 14-5

CHARACTER

MEANING

EXAMPLE

d

Short date

8/20/2011

D

Long date

Friday, August 20, 2011

f

Full date, short time

Friday, August 20, 2011 1:23 PM

F

Full date, long time

Friday, August 20, 2011 1:23:00 PM

g

General date/time, short time

8/20/2011 1:23 PM

G

General date/time, long time

8/20/2011 1:23:00 PM

M or m

Month day

August 20

O

Round trip

2011-08-20T13:23:00.0000000

R or r

RFC1123

Fri, 20 Aug 2011 13:23:00 GMT

s

Sortable date/time

2011-08-20T13:23:00

t

Short time

1:23 PM

T

Long time

1:23:00 PM

u

Universal sortable short date/time

2011-08-20 13:23:00Z

U

Universal sortable full date/time

Friday, August 20, 2011 1:23:00 PM

Y or y

Month, year

August, 2011

The DateTime class also provides several methods that return the date's value as a string formatted in the most common date and time formats. Table 14-6 summarizes the most useful of these methods and shows the results on my computer set up for US English. Your results will depend on how your computer is configured.

Table 14.6. TABLE 14-6

METHOD

FORMAT

EXAMPLE

ToLongDateString

Long date (D)

Friday, August 20, 2010

ToLongTimeString

Long time (T)

1:23:00 PM

ToShortDateString

Short date (d)

8/20/2010

ToShortTimeString

Short time (t)

1:23 PM

ToString

General date and time (G)

8/20/2010 1:23:00 PM

Custom Date and Time Formats

If the standard date and time formatting characters don't do the trick, you can use a custom format. Table 14-7 summarizes the custom date and time formatting strings. Note that for many of the characters in this table, the uppercase and lowercase versions have different meanings.

Table 14.7. TABLE 14-7

CHARACTER

MEANING

d

Day of month between 1 and 31.

dd

Day of month between 01 and 31.

ddd

Abbreviated day of week (Mon, Tue, and so on).

dddd

Full day of week (Monday, Tuesday, and so on).

f

Digits after the decimal for seconds. For example, ffff means use four digits.

F

Similar to f but trailing zeros are not displayed.

g

Era specifier. For example, A.D.

h

Hours between 1 and 12.

hh

Hours between 01 and 12.

H

Hours between 0 and 23.

HH

Hours between 00 and 23.

m

Minutes between 0 and 59.

mm

Minutes between 00 and 59.

M

Month between 1 and 12.

MM

Month between 01 and 12.

MMM

Month abbreviation (Jan, Feb, and so on).

MMMM

Month name (January, February, and so on).

s

Seconds between 0 and 59.

ss

Seconds between 00 and 59.

t

First character of AM/PM designator.

tt

AM/PM designator.

y

One- or two-digit year. If the year has fewer than two digits, is it not zero padded.

yy

Two-digit year, zero padded if necessary.

yyy

Three-digit year, zero padded if necessary.

yyyy

Four-digit year, zero padded if necessary.

yyyyy

Five-digit year, zero padded if necessary.

z

Signed time zone offset from GMT. For example, Pacific Standard Time is −8.

zz

Signed time zone offset from GMT in two digits. For example, Pacific Standard Time is −08.

zzz

Signed time zone offset from GMT in hours and minutes. For example, Pacific Standard Time is −08:00.

:

Hours, minutes, and seconds separator.

/

Date separator.

'ABC'

Literal string. Characters enclosed in single quotes are displayed without any conversion.

Table 14-8 shows some example formats and their results. The date used was 1:23:45.678 PM August 20, 2011 on my computer set up for US English. Your results will depend on how your computer is configured.

Table 14.8. TABLE 14-8

FORMAT

RESULT

M/d/yy

8/20/11

d MMM yy

20 Aug 11

HH:mm 'hours'

13:23 hours

h:mm:ss.ff, M/d/y

1:23:45.67, 8/20/11

dddd 'at' h:mmt

Friday at 1:23P

ddd 'at' h:mmtt

Fri at 1:23PM

TRY IT

In this Try It, you build a program that displays the current date and time in a Label when it starts, as shown in Figure 14-1.

FIGURE 14-1

Figure 14.1. FIGURE 14-1

Lesson Requirements

In this lesson:

  • Start a new project and add a Label to its form.

  • Give the form a Load event handler that sets the Label's text as shown in Figure 14-1.

Note

You can download the code and resources for this Try It from the book's web page at www.wrox.com or www.vb-helper.com/24hourvb.html. The programs can be found within the Lesson14 folder.

Hints

  • The DateTime.Now property returns the current date and time.

  • Either use String.Format or the value's ToString method to format the result.

Step-by-Step

  • Start a new project and add a Label to its form.

    1. Create the new project and its Label. Dock the label to the form and make it center its text.

  • Give the form a Load event handler that sets the Label's text as shown in Figure 14-1.

    1. Use code similar to the following:

      ' Display the current date and time.
      Private Sub Form1_Load() Handles MyBase.Load
          lblDateAndTime.Text = DateTime.Now.ToString(
              "'It is' h:mmtt 'on' ddd, MMM dd yyyy")
      End Sub

Note

Please select Lesson 14 on the DVD to view the video that accompanies this lesson.

EXERCISES

  1. Lesson 13's Try It reads and displays currency values, but it displays quantities without thousands separators. If you ordered 1,200 pencils, the program would display 1200.

    Copy that program (or download the Lesson 13 Try It from the book's web site) and modify it so quantities are displayed with thousands separators.

  2. Make a program that displays the time every second. (Hint: Use a Timer.)

  3. Copy the program that you built for Exercise 1 and modify it so the main form displays items in a ListBox instead of a ListView. Make the program use string.Format to add items to the ListBox in a format similar to the following:

    1,200 Gummy slugs at $0.02 each = $24.00
  4. Make a program that replaces all occurrences of the letter e in a string entered by the user with the character -.

Note

You can find solutions to this lesson's exercises in the Lesson14 folder inside the download available on the book's web site at www.wrox.com or www.vb-helper.com/24hourvb.html.

EXERCISES
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset