Set 14: Advanced String Methods

Skill 14.1 Apply Advanced String Methods
Skill 14.1 Concepts

The String methods and techniques we have encountered in previous lessons include concatenation, length(), substring(), toLowerCase(), toUpperCase(), escape sequences ("\n", "\t", etc), equals(), and equalsIgnoreCase()

We will now look at some of the signatures (and examples) of some of the more advanced String methods.

Recall that a signature is as follows:

returnType methodName (type parameter1, type parameter2, etc);

Below, we will look at several new methods associated with the String class

For all the examples below we will assume that "s" is a String as follows,

String s = "Take a Hike!"

Recall that the indices of the individual characters of this String are as follows,

character T a k e a H i k e !
index 0 1 2 3 4 5 6 7 8 9 10 11

public int compareTo(Object myObj)

The compareTo method accepts any Object, here we will specify a String object. The general syntax for usage of compareTo is shown below,

int j = s.compareTo("Idaho");
System.out.println(j);//prints 11

In the example above, 11 is printed because the first letter in "Take a Hike" is 11 places after the first letter in "Idaho" in the alphabet.

Now, let's consider the reverse,

int j = ("Idaho").compareTo(s);
System.out.println(j);//prints -11

In the above example, because the first letter in "Idaho" is 11 digits before the first letter in "Take a Hike", -11 is printed.

Now, let's consider what happens when we mix lower and upper case letters in our comparison. For example,

int j = ("idaho").compareTo(s);
System.out.println(j);//prints 21

The result above can be explained in terms of the char values assocated with first letters in "idaho" and "Take a Hike". The first letter, i, has a value of 105 and, T, has a value of 84. 105 - 84 = 21.

indexOf()

This method comes in 6 flavors (each is described below). For each case, all return negative one (-1) if the search is unsuccessful.

Signature Description Example
public int indexOf(String str) Search from left to right for the first occurrence of the String str. s = "The Walking Dead";
int j = s.indexOf("Walking");
System.out.println(j); //prints 4
public int indexOf(String s, int from) Starting at index, from, search from left to right for the first occurrence of the String s s = "The Walking Dead";

int j = s.indexOf("Walking", 7);
System.out.println(j); //prints -1

int j = s.indexOf("a", 7);
System.out.println(j); //prints 14
public int indexOf(char ch) Search from left to right for the first occurrence of the char ch s = "The Walking Dead";
int j = s.indexOf('W');
System.out.println(j); //prints 4
public int indexOf(int ascii) This method is very similar to the one above, except instead of a char we give the ASCII code of the char desired s = "The Walking Dead";
int j = s.indexOf(68); //ASCII code for 'D'
System.out.println(j); //prints 12
public int indexOf(char ch, int from) Starting at index from, search from left to right for the first occurrence of the char ch s = "The Walking Dead";
int j = s.indexOf('e', 4)
System.out.println(j); //prints 13
public int indexOf(int ascii, int from) This method is very similar to the one above, except instead of a character we give the ASCII code of the character desired. s = "The Walking Dead";
int j = s.indexOf(101, 4); //ASCII code for 'e'
System.out.println(j); //prints 13

public char charAt(int indx)

This method returns the character at the specified index.

s = "Take a Hike!";
char myChar = s.charAt(5);
System.out.println(myChar); //prints a

public String trim()

This method removes whitespace from both ends of the String while leaving interior whitespace intact. (Whitespace consists of new line (\n), tab (\t), and spaces)

s = "Take a Hike!";
s = "\t\t" + s + "\n";//add some space before and after
System.out.println("X" + s.trim() + "X"); //prints XTake a HikeX

public boolean contains(String ss)

This method returns true when this String contains the String ss; otherwise, false

boolean b = "Sticks and Stones".contains("tic"); //returns true

Skill 14.1: Exercises 1 thru 2
Skill 14.2 Parse Strings with a Scanner
Skill 14.2 Concepts
Pass a String to a Scanner

In a previous lesson we learned how to use the Scanner class to input text from the keyboard. Here, we illustrate further uses of Scanner in parsing (processing) a String. Instead of passing System.in to the Scanner as we did for the keyboard input, we pass a String as follows,

Scanner sc = new Scanner(“Please, no more Exams!”);

Once a String is passed to the Scanner, it is possible to anaylze it. The process of analyzing a String or text is called parsing.

Delimiters

A delimiter is a series of characters that separate the text presented to a Scanner object into separate chunks called tokens. The default delimiter is whitespace. The tokens that make up the String below could be accessed using the next() method.

Scanner sc = new Scanner(“Please, no more Exams!”);

String firstWord = sc.next(); //Please,
String secondWord = sc.next(); //no
String thirdWord = sc.next(); //more
String lastWord = sc.next(); //Exams!

The useDelimiter method allows us to create a custom delimiter.

Scanner sc = new Scanner(“Please, no more Exams!”);

sc.useDelimiter(“,\\s”); //the delimiter is the comma followed by a space
sc.next(); //Please
sc.next(); //no more Exams!

hasNext()

The hasNext() method is useful for evaluating whether or not another token exists. If another token exists hasNext() will return true, otherwise it will return false

Scanner sc = new Scanner(“Please, no more Exams!”);

sc.useDelimiter(“,\\s”); //the delimiter is the comma followed by a space

while(sc.hasNext()){

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

}

Skill 14.2: Exercise 1