Week 5 - Lecture 1 - Chapter 9
Week 5 - Lecture 1 - Chapter 9
CHAPTER 9 STRINGS
java.lang.String
+indexOf(ch: char): int Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
+indexOf(ch: char, fromIndex: Returns the index of the first occurrence of ch after fromIndex in
int): int the string. Returns -1 if not matched.
+indexOf(s: String): int Returns the index of the first occurrence of string s in this string.
Returns -1 if not matched.
+indexOf(s: String, fromIndex: Returns the index of the first occurrence of string s in this string
int): int after fromIndex. Returns -1 if not matched.
+lastIndexOf(ch: int): int Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
+lastIndexOf(ch: int, Returns the index of the last occurrence of ch before fromIndex
fromIndex: int): int in this string. Returns -1 if not matched.
+lastIndexOf(s: String): int Returns the index of the last occurrence of string s. Returns -1 if
not matched.
+lastIndexOf(s: String, Returns the index of the last occurrence of string s before
fromIndex: int): int fromIndex. Returns -1 if not matched.
FINDING A CHARACTER OR A
SUBSTRING
3
IN A STRING
The String class provides several static valueOf methods for converting a
character, an array of characters, and numeric values to strings. These methods
have the same name valueOf with different argument types char, char[], double,
long, int, and float.
For example, to convert a double value to a string, use String.valueOf(5.44). The
return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’.
CONVERTING STRINGS TO INTEGER AND
DOUBLE
6
USING INTEGER.PARSEINT( ) AND
DOUBLE.PARSEDOUBLE( )
As a result n will contain the integer value 12 and m will contain the
double value 12.5.
Note that if s1 or s2 contain non digit characters then an error will
occur. Of course s2 can contain the dot.
PROGRAMMING EXERCISE 9.4 IN YOUR
TEXTBOOK
7
PAGE 363: OCCURRENCES OF A
SPECIFIED CHARACTER IN A STRING
Write a test program (main method) that prompts the user to enter a string
followed by a character and displays the number of occurrences of the character in
the string.
SOLUTION OF PROGRAMMING EXERCISE 9.4
import java.util.Scanner;
8
public class Exercise09_04 {
String s = input.next();
char ch = input.next().charAt(0);
System.out.println(counter);
int counter = 0;
if (str.charAt(i) == ch)
counter++;
return counter;
}
PROGRAMMING EXERCISE 9.6 IN YOUR
TEXTBOOK
9
PAGE 363: COUNTING THE
LETTERS IN A STRING
String s = input.nextLine();
int count = 0;
count++;
return count;