complete-reference-vb_net_17
complete-reference-vb_net_17
IndexOf, LastIndexOf
The IndexOf and LastIndexOf methods provide a facility for locating a character or a set of characters in a
String object. In a word processing application, for example, you will want to provide your users with the
facility of searching for and replacing strings. Consider the following code snippet:
It is rather easy to work out in your head the output to the console. It is the integer 38 of coursebeing the last
character in the above String object. If the character is not present in the String, a return value of 1 is
reported.
The method LastIndexOf provides a slightly different facility. It reports the last occurrence of a particular
character in the String. In the preceding example, there are two occurrences of "x" so the return value is 41.
But if we searched for "o" we could get 17 as the return value because there are two occurrences of "o" in the
String, and we are looking for the last one.
Insert
The Insert method inserts a String into another String in a location specified in the method. Consider the
following code:
The String argument "very expensive" is inserted at integer 4 in the String s1 to display to the console the
following:
Intern, IsInterned
Often, String objects can get quite large, and the task of comparing them can become quite slow in
computing terms. The Intern method provides a facility for obtaining a reference to a String that speeds up
comparison operations by an order of magnitude. The Intern method is also useful for creating Strings
on−the−fly and then providing an immediate facility for using the String in a number of operations.
When you invoke the Intern method of different String objects that have the same content as the original
String object, you will obtain a reference to the first object. For every object instantiated that is the same as
the original object, you will obtain multiple references to the same object by interning each new String object.
Interned Strings can be compared with the = operator (equals) instead of calling the more resource−intensive
equals operator, which literally has to compare each character in the corresponding String.
501