String is a class and thus are manipulated using methods
+), which also happens to be the only operator
in the language that operates on an object of a class (all other operators work on what are called the
primitive types: int, double, boolean, char).
String.
equals method
String object is the empty string — ""
String object prior to building it
up (usually via concatenation). This is similar to initializing and integer to 0 prior to using it as a total.
String class by going to the API and looking up the class.
String object — the String class is said to be
immutable.
String objects produce a new String object; the
original object remains unchanged.
String class is the first class whose methods we will
be using in a nontrivial manner; as such the relevant terminology can be helpful.
Scanner scanner; … scanner.nextInt()
scanner
scanner is thus often called the receiver
scanner
is an object of the class Scanner
nextInt
Scanner does indeed have a method named nextInt
nextInt method in the Scanner class that accepts no arguments
nextInt
methods in the Scanner that accept different signatures (number/types of arguments)
scanner.nextInt() is sometime called a message
| Message | scanner.nextInt()
|
| Receiver | scanner
|
| Method | nextInt
|
| Argument(s) | none
|
PrintStream ps;
…
ps.println("Hello");
| Message | ps.println("Hello")
|
| Receiver | ps
|
| Method | println
|
| Argument(s) | "Hello"
|
Math.sqrt(25);
static in the method header).
| Message | Math.sqrt(25)
|
| Receiver | none
|
| Method | sqrt
|
| Argument(s) | 25
|
String class.
lengthint length()
length returns the number of characters in the receiver
String s = "Hello"; System.out.println(s.length()); // Outputs 5
lemgth used used in a manner similar to the .length field of an array;
i.e., as the limit in a for loop traversing the string (array).
String s = … for (int i = 0; i < s.length(); i++) … // loop will be executed for as many characters as are in the string
length for String is a method; i.e., it
is invoked as a method (with ()'s); while the length associated with
an array is not invoked as a method, but rather treated like a variable — arr.length —
we call it a field (more on that in 3115).
charAt
char charAt(int index)
String class is often based on an array of chars.)
string start at index 0.
[] operator does not work on objects of the String class; instead you must use the
charAt method
charAt is an accessor/get method, i.e., it retrieves a particular character of the
string; there is no corresponding mutator/set method to modify a particular character position in the string.
String s = "Hello"; System.out.println(s.charAt(0)); // OutputsHSystem.out.println(s.charAt(s.length()-1)); // Outputso
charAt is used to extract individual characters from the string. It often appears in the body of a for loop (with length()
in the loop header — see above) that traverses the string 'visiting'/processing each character
String s = … for (int i = 0; i < s.length(); i++) System.out.println(s.charAt(i)); // print each character of the string on a separate line
indexOf, lastIndexOfint indexOf(String str)
str in the receiver, or -1 if not present
int indexOf(String str, int fromIndex)
str in the receiver, starting
at fromIndex, or -1 if not present
int lastIndexOf(String str)
str in the receiver, or -1 if not present
int lastIndexOf(String str, int fromIndex)
str in the receiver, searching backward starting
t fromIndex, or -1 if not present
indexOf and lastIndexOf are analogous to the
// 1 2 3 4
// 0123456789012345678901234567890123456789012345
String s = "Orange juice, apple juice, and pineapple juice";
System.out.println(s.indexOf("juice")); // Outputs 7
System.out.println(s.indexOf("juice", 8)); // Outputs 20
System.out.println(s.lastIndexOf("juice")); // Outputs 41
System.out.println(s.lastIndexOf("juice", 40)); // Outputs 20
indexOf is used to search a string for the occurrence of some string or character;
e.g. looking for a blank, a punctuation mark, or some particular word. The typical coding pattern is to start off (actually, prime the pump) with the one-argument version —
which begins at the beginning of the string to be searched, and then use the two-argument method to continue from that point if one wishes to
find ALL the occurrences, rather than simply the first one. lastIndex does the same thing but backwards; i.e., starting from the end of
the string, and searching towards the beginning.
String s = …
int pos = s.indexOf(" ");
while (pos >= 0) {
…
pos = s.indexOf(" ", pos+1); // continue searching from the most recent blank's position + 1
}
substringString substring(int beginIndex)
beginIndex to the end of the string
String substring(int beginIndex, int endIndex)
beginIndex to endIndex-1
endIndex is the position after the last desired character
arr.length is the
position after the last element of the array).
String s = "Orange juice"; System.out.println(s.substring(1, 6); // OutputsrangeSystem.out.println(s.substring(7); // Outputsjuice
substring returns a new String object; the receiver remains unchanged
substring is used to extract portions of a string; e.g. the words of a sentence. It is often used in conjunction
with indexOf; e.g. we use indexOf (as above) to move through a string finding a pattern (e.g., the blanks), and then
extract either the pattern of something in the 'neighborhood of the pattern (e.g.the words in between the blanks) using substring
equalsanotherString and returns true if they are lexically equal,
i.e., they consist of the exact same sequence of characters)
==) has a somewhat different behavior; it returns true only if the
objects being compared are the same object (see the examples below).
String
s1 = new String("Hello"),
s2 = new String("Hello");
System.out.println(s1 == s1); // Outputs true
System.out.println(s1 == s2); // Outputs false
System.out.println(s1.equals(s1)); // Outputs true
System.out.println(s1.equals(s2)); // Outputs true
equals is the way in which objects in general are compared for equality (as opposed to ==).
compareToint compareTo(String anotherString)
anotherString) and returns:
< 0 if the receiver is lexically less than anotherString
0 if the receiver is lexically equal to anotherString
equals method
> 0 if the receiver is lexically greater than anotherString
String s1 = "Cat", s2 = "Dog", s3 = "AAAAAAAAA", s4 = "Z", s5 = "ZZZZZ", s6 = "a"; System.out.println(s1.compareTo(s2)); // Outputs-1System.out.println(s1.compareTo(s1)); // Outputs0System.out.println(s4.compareTo(s3)); // Outputs1System.out.println(s5.compareTo(s6)); // Outputs-1
compareTo is the way in which objects are compared in general (as opposed to <, >, etc; operators
are not available for use with objects).
trimString trim()
public class FunWithStrings {
public static void main(String [] args) {
String s = "Hello";
System.out.println( '|' + s + '|'); // "Hello"
s = "J" + s.substring(1);
System.out.println( '|' + s + '|'); // "Jello"
s = s.substring(0, s.length()-1) + "y";
System.out.println( '|' + s + '|'); // "Jelly"
s += " Belly";
System.out.println( '|' + s + '|'); // "Jelly Belly"
int index = s.indexOf(" ");
s = "Peanut Butter and " + s.substring(0, index);
System.out.println( '|' + s + '|'); // "Peanut Butter and Jelly"
index = s.indexOf("Jelly");
s = s.substring(index) + " Roll Morton";
System.out.println( '|' + s + '|'); // "Jelly Roll Morton"
s = s.substring(s.lastIndexOf(" ")+1) + " Salt";
System.out.println( '|' + s + '|'); // "Morton Salt"
index = s.indexOf(" ");
s = s.substring(0, index) + " Iodized" + s.substring(index);
System.out.println( '|' + s + '|'); // "Morton Iodized Salt"
}
}
String MethodsString, e.g. "juice", or int e.g. 7, 40).
indexOf is used to search for a particular pattern, and the returned index is then
used as the index argument for one or more of the manipulation methods (e.g., substring)
length method is often used (in conjunction with these indexes) to make sure one does not
go beyond the end of the string.
There are two basic ways of processing strings:
for loop in conjunction with the charAt method
void printVowels(String s) {
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I' ||
s.charAt(i) == 'O' || s.charAt(i) == 'U' ||
s.charAt(i) == 'a' || s.charAt(i) == 'e' ||
s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u')
System.out.println(s.charAt(i);
}
void printVowels(String s) {
for (int i = 0; i < s.length(); i++)
if ("AEIOUaeiou".indexOf(s.charAt(i)) >= 0)
System.out.println(s.charAt(i);
}
void count(String s, char c) {
int result = 0;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == c) result++;
return result;
}
while loop
indexOf (or lastIndexOf) to move around the string, looking for things
while, rather than a for loop is typically used
int count(String s, String pattern) {
int result = 0;
int index = s.indexOf(pattern);
while (index >= 0) {
result++;
index = s.indexOf(pattern, index+1);
}
return result;
}
import java.io.*;
import java.util.*;
public class Program_16_1 {
public static void main(String [] args) throws Exception {
Scanner scanner = new Scanner(new File("document.text"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
int start = 0;
int index = line.indexOf(' ');
while (index >= 0) {
String word = line.substring(start, index);
System.out.println(word);
start = index+1;
index = line.indexOf(' ', index+1);
}
String word = line.substring(start);
System.out.println(word);
System.out.println();
}
}
}
The basic idea here is to:
indexOf to look for the blanks, then use substring to extract the word.
indexOf call
indexOf returns -1)
import java.io.*;
import java.util.*;
public class Program_16_2 {
public static void main(String [] args) throws Exception {
Scanner scanner = new Scanner(new File("document.text"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
int i = 0;
while (i < line.length()) {
char c = line.charAt(i);
while (i < line.length() && !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
i++;
if (i < line.length()) c = line.charAt(i);
}
String word = "";
while (i < line.length() && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) {
word += line.charAt(i);
i++;
if (i < line.length()) c = line.charAt(i);
}
System.out.println(word);
}
System.out.println();
}
}
}
The basic idea here is to:
Character ClasscharAt method are of type char (a primitive type).
Character class contains (static) methods that can be used to contain information about a character; e.g., if it's
an upper case letter, a lower case, a digit, a punctiation mark, etc
boolean isUpperCase(char c) — returns true if c is an uppercase letter
c >= 'A' && c <= 'Z'
boolean isLowerCase(char c) — returns true if c is a lowercase letter
c >= 'a' && c <= 'z'
boolean isLetter(char c) — returns true if c is an uppercase or lowercase letter
c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'
isUpperCase(c) || isLowerCase(c)
boolean isDigit(char c) — returns true if c is a (decimal) digit
c >= '0' && c <= '9'
boolean isWhitespace(char c) — returns true if c is whitespace, i.e.,
blank, tab, and certain other 'whitespace' characters.
Character class character-testing methods.
import java.io.*;
import java.util.*;
public class Program_16_3 {
public static void main(String [] args) throws Exception {
Scanner scanner = new Scanner(new File("document.text"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
int i = 0;
while (i < line.length()) {
while (i < line.length() && !Character.isLetter(line.charAt(i)))
i++;
String word = "";
while (i < line.length() && Character.isLetter(line.charAt(i))) {
word += line.charAt(i);
i++;
}
System.out.println(word);
}
System.out.println();
}
}
}
The approach is the same as Program 16.2, except the characters are tested using the Character methods rather than
direct conditionals.