30.07.2013 Views

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

Visual Basic.NET How to Program (PDF)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 15 Strings, Characters and Regular Expressions 637<br />

access an element outside the bounds of the character array, an ArgumentOutOfRangeException<br />

is thrown.<br />

Line 23 assigns <strong>to</strong> string4 a new String object, using the String construc<strong>to</strong>r<br />

that takes as arguments a character and an Integer specifying the number of times <strong>to</strong><br />

repeat that character in the String.<br />

Each instance of variable quotes (lines 25–28) represents a double quote character<br />

("). <strong>Visual</strong> Studio .<strong>NET</strong> treats double quotes as delimiters for Strings and does not treat<br />

them as part of a String. We can represent a quotation mark within a String by using<br />

the numerical code of the character (e.g., line 11) or by placing consecutive double quote<br />

characters ("") in the String.<br />

15.4 String Length and Chars Properties, and CopyTo<br />

Method<br />

The application in Fig. 15.2 presents the String property Chars, which facilitates the<br />

retrieval of any character in the String, and the String property Length, which returns<br />

the length of the String. The String method CopyTo copies a specified number<br />

of characters from a String in<strong>to</strong> a Char array.<br />

1 ' Fig. 15.2: StringMiscellaneous.vb<br />

2 ' Using properties Length and Chars, and method CopyTo<br />

3 ' of class string.<br />

4<br />

5 Imports System.Windows.Forms<br />

6<br />

7 Module modMiscellaneous<br />

8<br />

9 Sub Main()<br />

10 Dim string1, output As String<br />

11 Dim characterArray As Char()<br />

12 Dim i As Integer<br />

13 Dim quotes As Char = ChrW(34)<br />

14<br />

15 string1 = "hello there"<br />

16 characterArray = New Char(5) {}<br />

17<br />

18 ' output string<br />

19 output = "string1: " & quotes & string1 & quotes<br />

20<br />

21 ' test Length property<br />

22 output &= vbCrLf & "Length of string1: " & string1.Length<br />

23<br />

24 ' loop through characters in string1 and display<br />

25 ' reversed<br />

26 output &= vbCrLf & "The string reversed is: "<br />

27<br />

28 For i = string1.Length - 1 To 0 Step -1<br />

29 output &= string1.Chars(i)<br />

30 Next<br />

Fig. 15.2 String Length and Chars properties, and CopyTo method (part 1<br />

of 2).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!