17-1

Following is a list of some of the
,
,
sequences.

methods and techniques we encountered in Lesson 3:
,
,
, and escape

In Lesson 9 we studied how to compare
equals( ) and equalsIgnoreCase( )

s:

We will now look at some of the
(and examples) of some of the more advanced
methods. Recall from Lesson 15 that the layout of a signature is as follows:
public returnType methodName( type parameter1, type parameter2, …)
The variable

and

could be

,

For the examples below assume that is a
s = “The Dukes of Hazzard”

,

,

,

, etc.

as follows:

For convenience, the indices of the individual characters of this
T h e
D u k e s
o f
H a z z a r d
| | | | | | | | | | | | | | | | | | | |
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

are given below:

Notice this method accepts any Object. Here, we will specifically use a
object.
The general syntax for usage of
is:
This method has three rules:
a. If alphabetically precedes “coat room” then it returns a negative .
b. If alphabetically comes after “coat room” it returns a positive .
c. If is alphabetically equal to “coat room” then it returns zero.
System.out.println( s.compareTo(“coat room”)); //
The reason we get a negative number in the example above is because ‘T’ alphabetically
precedes ‘c’. Refer back to Lesson 13 and you will see that the ASCII code for capital ‘T’
is 84 and the ASCII code for little ‘c’ is 99. The number 84 comes before 99 so we say
that “The Dukes of Hazzard” comes before (or alphabetically precedes) “coat room”.
There is another version of

,

that is not case sensitive.

This method comes in 6 flavors: (All return –1 if the search is unsuccessful.)

Search from left to right for the first occurrence of the
int j = s.indexOf(“Hazzard”);
System.out.println(j); //

.

17-2

Starting at index

, search from left to right for the first occurrence of the

int j = s.indexOf(“Hazzard”, 15);
System.out.println(j); // …it couldn’t find it when starting at 15
int j = s.indexOf(“e”, 4);
System.out.println(j); // . First “e” is at 2, but we started searching at 4

Search from left to right for the first occurrence of the
int j = s.indexOf(‘D’);
System.out.println(j); //

This method is very similar to c. above, except, instead of a character we give
the ASCII code of the character desired.
int j = s.indexOf(68); // ASCII code for ‘D’ is 68
System.out.println(j); //

Starting at index

, search from left to right for the first occurrence of the

int j = s.indexOf(‘e’, 4);
System.out.println(j); //

This method is very similar to e. above, except, instead of a character we give
the ASCII code of the character desired.
int j = s.indexOf(101, 4); // ASCII code for ‘e’ is 101
System.out.println(j); //
This method also comes in 6 flavors: (All return –1 if the search is unsuccessful.)
These are exactly the same as the
method, except here, we begin searching
from the right side of the
instead of the left as with
. Only two
examples will be given since they are so similar to the previous examples.

17-3
int j = s.lastIndexOf(“Haz”);
System.out.println(j); //
int j = s.lastIndexOf(“Haz”, 11);
System.out.println(j); //

This method returns the character at the specified index.
char myChar = s.charAt(6);
System.out.println(myChar); //
This method replaces

occurrences of the character

with the character

.

String myString = s.replace(‘z’, ‘L’);
System.out.println(myString); //
This method replaces

occurrences of

with

.

String myString = s.replace(“Dukes”, “Nerds”);
System.out.println(myString); //
while leaving interior
This method removes whitespace from both ends of the
whitespace intact. (Whitespace consists of \n, tab (\t), and spaces.)
String s = “\t Ding Dong \t \n ”
System.out.println(“X” + s.trim( ) + “X”); //
This method returns

when this

contains the

; otherwise,

.

boolean b = “Sticks and Stones”.contains(“tic”)
This methods returns

when this

contains

as its leading substring.

boolean b = “Have a good day.”.startsWith(“Hav”); //

In Lesson 7 we learned how to use the
class to input text from the keyboard. Here, we
illustrate further uses of
in parsing a
. Instead of passing
to the
constructor as we did for keyboard input, we pass a
to the constructor as follows:

17-4
Scanner sc = new Scanner(“Please, no more homework!”);
A delimiter is a series of characters that separates the text presented to a
object
into separate tokens. The default delimiter is whitespace, so the separate tokens produced
by repeated application of the
method in the above example would be “Please,”,
“no”, “more”, and “homework!”. The
method allows a custom delimiter to
be set using regular expressions (see Appendix AC).
One of the key concepts here is that of the “position” of the
object as it scans its
way through the
. We will always think of this position as being
two
characters in the same way that a cursor in a word processor is never
a character;
rather it is always
two characters (or perhaps preceding the first character, or
just after the last character). As tokens are returned by
, etc., the position advances to
just after the last token returned.
Let us consider the following sequence of code where a
is passed to the
constructor of the
class as we illustrate the concept of position. We are also
going to introduce the
,
,
, and
methods
(all use regular expression arguments… see Appendix AC). These methods will
; rather, their functions will be
:
Scanner sc = new Scanner("A string for testing scanner");
//The default delimiter of whitespace will be used.
System.out.println(sc.next( ));
//
System.out.println(sc.findInLine("ri"));
//
String ns = sc.next( ); //next( ) returns a String
System.out.println(ns);
//
sc.useDelimiter("r\s+");
//
System.out.println(sc.next( ));
//
sc.skip(“r\s*test”);
//

A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner
|
A string for testing scanner

System.out.println(sc.next( ));
//

|

We should take note of several salient features from this example:

1. The position of a
object always moves
up”. Likewise, searches (as with
e and
current position.

. It can never be “backed) always move
from the

2. Starting from the current position and moving forward, the
method
searches ahead
to find the specified substring. Notice above that
the “ri” sought after does
have to
follow the current position.
If the substring is not found, a

is returned.

17-5
3. In the
method the specified substring
indeed need to
follow
the current position. The “r test” sought after needs to immediately follow the current
position.
If the substring is not found, a

is thrown (an error).

In addition to the searching methods
and
, there is another that can sometimes
be useful,
. This is identical to
except
for the additional parameter,
, which limits the search for
to the next
characters. If the search is to be successful,
must be found in its
within
is zero the search is allowed to continue to the end of the text if
characters. If
necessary.
Let’s consider what happens when there are two delimiters
as illustrated by the following code:
String ss = "abcxyxydef";
Scanner sc = new Scanner(ss);
sc.useDelimiter("xy");
while(sc.hasNext( ))
{
System.out.println(sc.next( ));
}
The resulting printout is:
abc
def
The blank line is an

that was “between” the two successive delimiters.

In order to refine our understanding of the
,
and
, consider how an email-spammer might try to disguise a word for the purpose of
getting past a spam filter. Instead of transmitting something like “Low cost loans”, the
trick is to send a similar phrase with intervening characters like, “L*o*w* *c*o*s*t*
l o*a*n*s”. Notice this is still readable; however, a standard spam filter would be
defeated.
In the first line of code below we see an attempt at disguising the word “dirty”.
The remainder of the code strips away the superfluous characters leaving only the
original word so that the spam filter can properly detect it.
String s = "d^^*_^^ir....-t***y"; //"dirty"
Scanner sc = new Scanner(s);
sc.useDelimiter(""); //set delimiter to nothing which makes every character a token
String answer = "";

17-6
while(sc.hasNext( ))
{
//skip the stuff we want to get rid of
while(sc.hasNext("\W|_"))
{
sc.skip("_*"); //skip underscores
if(sc.hasNext( ))
sc.skip("\W*"); //skip non-word characters.Word characters are[a
//zA-Z_0-9]
}
if(sc.hasNext( ))
answer = answer + sc.next( );
}
System.out.println(answer); //prints

In Lesson 7 we learned to input text from the keyboard by creating a
object by passing
to the constructor. There, we directly used this
object to parse the input
with
,
, etc. To avoid some strange effects, it is suggested that all the input be
immediately stored into a
using
and then passed to a
object. Then
parse this second
object using
,
,
, etc.

Consider the following program that allows something like
to be entered as
input from the keyboard. A
object then uses the plus signs (and any adjoining
whitespace) as delimiters and produces the sum of these numbers(1523).
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1,345 +137 : ");
String s = kb.nextLine( ); //Best to store in a String and then create a new Scanner
//object; otherwise, it can get stuck waiting for input.
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\s*\+\s*");
int sum = 0;
while(sc.hasNextInt( ))
{
sum = sum + sc.nextInt( );
}
System.out.println("Sum is: " + sum);
}
}

Enter something like 8 + 33 + 1,345 +137
Sum is: 1523

:

8 + 33 + 1,345 + 137

Enter something like 8 + 33 + 1,345 -137
Sum is: 1249

:

8 + 33+ 1,345 -137

Exercise on Lesson 17

Project… Encryption/Decryption
encrypt
String

decrypt

String

String
String

Tester

Enter a sentence that is to be encrypted: This is a very big morning.
Original sentence = This is a very big morning.
Encrypted sentence = This is a ag',rery dug>?/ijeb..w ssadorninjeb..w.
Decrypted sentence = This is a very big morning.