Title: Strings and Characters
1Strings and Characters
2Overview
- Create and manipulate String objects
- Create and manipulate StringBuffer objects
- Create and manipulate Character objects (not the
primitive data type) - Use the StingTokenizer object to break Strings
into tokens
3String Objects
- A String is an object and not a primitive data
type - A String is made up of one or more characters
- String constants (literals) are enclosed in
double quotes - A String object is immutable, cannot be directly
changed
4String Object Constructors
String() String(String s) String(char
c) String(byte b) String(char c, int offset,
int number) String(byte b, int offset, int
number) String(StringBuffer sb) (shortcut method
-- string value)
5String Methods
int length() char charAt(int index) void
getChars(int start, int end1, char c, int
into-index) boolean equals(Object o) -- NOT
boolean equalsIgnoreCase(String s) int
compareTo(String s) -- negative, zero, or
positive returned boolean regionMatches(boolean
ignoreCase, int start, String s, int start, int
number-of-characters)
6String Methods
boolean startsWith(String s) boolean
startsWith(String s, int index) boolean
endsWith(String s) int hashCode() int
indexOf(String s) -- negative if not found int
indexOf(int c) -- integer value of character --
e.g. l int indexOf(String s, int
start-index) int indexOf(int c, int start-index)
7String Methods
int lastIndexOf(String s) int lastIndexOf(int
c) int lastIndexOf(String s, int high-index) --
backward from index int lastIndexOf(int c, int
high-index) String substring(int
start-index) String substring(int start-index,
int end-index1) String concat(String s) -- also
done with operator
8String Methods
String replace(char old, char new) String
toUpperCase() String toLowerCase() String
trim() char toCharArray() static String
valueOf(primitive data type) static String
valueOf(char c) static String valueOf(char c,
int index, int size)
9Some String Method Examples
class StringExample public static void
main(String args) String c "Come
Prepared to Learn" String l new
String("Leave Prepared to Succeed") String
temp1 System.out.println(c "\n" l)
System.out.println("\nLength " c.length())
10String Method Examples
System.out.println("\nLength "
c.length()) System.out.println("equals
method " c.equals("come prepared to
learn")) System.out.println("equalsIgnoreCa
se method " c.equalsIgnoreCase("come
prepared to learn")) System.out.println("co
mpareTo method " l.compareTo("Leave
Prepared to Succeed Again"))
System.out.println("regionMatches method "
c.regionMatches(5, "Prepared", 0, 8))
System.out.println("indexOf(String) method "
l.indexOf("to")) System.out.println(
"indexOf(character) method "
l.indexOf('l'))
11String Method Examples
System.out.println("substring method "
c.substring(5, 13))
System.out.println("concat method "
c.concat(l)) System.out.println("replace
method " c.replace('e', 'Z'))
System.out.println("toUpperCase method "
l.toUpperCase()) System.out.println("toL
owerCase method " c.toLowerCase())
temp1 String.valueOf(173.458)
System.out.println("valueOf double "
temp1) System.out.println()
System.out.println(c "\n" l)
12String Method Examples
D\QM281\examplesgtjava StringExample Come
Prepared to Learn Leave Prepared to
Succeed Length 22 equals method
false equalsIgnoreCase method true compareTo
method -6 regionMatches method
true indexOf(String) method 15 indexOf(character)
method -1 substring method Prepared concat
method Come Prepared to LearnLeave Prepared to
Succeed replace method ComZ PrZparZd to
LZarn toUpperCase method LEAVE PREPARED TO
SUCCEED toLowerCase method come prepared to
learn valueOf double 173.458 Come Prepared to
Learn Leave Prepared to Succeed
13Method String intern()
- Used to get references to Strings
- If two Strings have the same contents, then using
the intern() method will return the same
reference which can be compared with the
operator - Used for efficiently comparing large Strings
14intern() method
class Intern public static void main
(String args) String s1, s2, s3, s4
s1 new String("qmcs rules") s2 new
String("qmcs rules") if (s1 s2)
System.out.println("s1 and s2 have same
reference") if (s1.equals(s2))
System.out.println("s1 and s2 have the same
contents") s3 s1.intern() s4
s2.intern() if (s3 s4)
System.out.println("s3 and s4 have the same
reference")
15intern() Method
D\QM281\examplesgtjava Intern s1 and s2 have the
same contents s3 and s4 have the same reference
16StringBuffer Class
- StringBuffer objects can be directly changed
- Can specify capacity (number of characters)
- If you run out of capacity, it is automatically
extended - Better for strings that are changing frequently
(dynamic strings)
17StringBuffer Constructors
StringBuffer() StringBuffer(int
capacity) StringBuffer(String s)
18StringBuffer Methods
int length() int capacity() void
ensureCapacity(int minimum) void setLength(int
size) -- may truncate object char charAt(int
index) void setCharAt(int index, char c) void
getChars(int start, int end, char dest, int
destindex) StringBuffer reverse() -- reverses
characters
19StringBuffer append Methods
StringBuffer append(primitive data
type) StringBuffer append(String s) StringBuffer
append(Object o) StringBuffer append(char c,
int start-index, int size) Remember You dont
have to do anything with what is returned!
20StringBuffer insert and delete
StringBuffer insert(int index, primitive-data-type
) StringBuffer insert(int index, String
s) StringBuffer insert(int index, Object
o) StringBuffer insert(int index, char
c) StringBuffer delete(int start-index, int
end-index1)
21StringBuffer Example
class SBuff public static void main(String
args) StringBuffer buf new
StringBuffer() String joe "Joe Komar"
String teach "teacher" String isa
"is a" double pay 18500.00
22StringBuffer Example
buf.append(joe) buf.append(" " isa
" " teach) System.out.println(buf)
System.out.println("length " buf.length()
" capacity " buf.capacity())
buf.insert(15, "great ")
System.out.println(buf) buf.insert(15,
pay) System.out.println(buf)
buf.setCharAt(21, ' ') System.out.println(b
uf)
23StringBuffer Example
System.out.println(buf.reverse())
buf.reverse() buf.delete(15, 22)
System.out.println(buf)
24StringBuffer Example
D\QM281\examplesgtjava SBuff Joe Komar is a
teacher length 22 capacity 34 Joe Komar is a
great teacher Joe Komar is a 18500.0great
teacher Joe Komar is a 18500. great
teacher rehcaet taerg .00581 a si ramoK eoJ Joe
Komar is a great teacher
25Character Class
- Wrapper class for the char primitive data type
- Has many static methods for testing the type of
character and to do case conversions - One constructor and a few non-static methods for
Character objects
26Character static methods
static boolean isDefined(char c) static boolean
isDigit(char c) static boolean isLetter(char
c) static boolean isLetterOrDigit(char c) static
boolean isLowerCase(char c) static boolean
isUpperCase(char c) static char toLowerCase(char
c) static char toUpperCase(char c)
27Character non-static methods
char charValue() -- returns the char value String
toString() int hashCode() boolean equals(Object
obj)
28StringTokenizer Class
- Breaks a string into component parts called
tokens - Tokens are separated by delimiters
- default is white space (blank, tab, newline,
carriage return) - other characters such as / or are also used as
delimiters - Used extensively in compiler writing and text
analysis
29StringTokenizer constructors
StringTokenizer(String s) StringTokenizer(String
s, String delim) StringTokenizer(String s, String
delim, boolean include-delim)
30StringTokenizer methods
int countTokens() boolean hasMoreTokens() String
nextToken() String nextToken(String delim)
31StringTokenizer Example
import java.util. class Toker public
static void main(String args)
StringTokenizer st1 String s "Able,
Baker, Charlie." st1 new
StringTokenizer(s, ", ") while
(st1.hasMoreTokens())
System.out.println(st1.nextToken())
32StringTokenizer Example
D\QM281\examplesgtjava Toker Able Baker Charlie.
33Using the Scanner Class
import java.util.Scanner public class
PigLatin public static void main (String
args) String sentence, result,
another Scanner scan new Scanner
(System.in) do
System.out.println ()
System.out.println ("Enter a sentence (no
punctuation)") sentence
scan.nextLine() System.out.println ()
result PigLatinTranslator.translate
(sentence) System.out.println ("That
sentence in Pig Latin is")
System.out.println (result)
System.out.println () System.out.print
("Translate another sentence (y/n)? ")
another scan.nextLine() while
(another.equalsIgnoreCase("y"))
34Using the Scanner Class
import java.util.Scanner public class
PigLatinTranslator public static String
translate (String sentence) String
result "" Scanner scan new Scanner
(sentence) sentence sentence.toLowerCase(
) while (scan.hasNext())
result translateWord (scan.next())
result " " return result
35Using the Scanner Class
private static String translateWord (String
word) String result "" if
(beginsWithVowel(word)) result word
"yay" else if (beginsWithBlend(wor
d)) result word.substring(2)
word.substring(0,2) "ay" else
result word.substring(1) word.charAt(0)
"ay" return result
36Using the Scanner Class
private static boolean beginsWithVowel (String
word) String vowels "aeiou"
char letter word.charAt(0) return
(vowels.indexOf(letter) ! -1)
37Using the Scanner Class
private static boolean beginsWithBlend
(String word) return ( word.startsWith
("bl") word.startsWith ("sc")
word.startsWith ("br") word.startsWith ("sh")
word.startsWith ("ch")
word.startsWith ("sk")
word.startsWith ("cl") word.startsWith ("sl")
word.startsWith ("cr")
word.startsWith ("sn")
word.startsWith ("dr") word.startsWith ("sm")
word.startsWith ("dw")
word.startsWith ("sp")
word.startsWith ("fl") word.startsWith ("sq")
word.startsWith ("fr")
word.startsWith ("st")
word.startsWith ("gl") word.startsWith ("sw")
word.startsWith ("gr")
word.startsWith ("th")
word.startsWith ("kl") word.startsWith ("tr")
word.startsWith ("ph")
word.startsWith ("tw")
word.startsWith ("pl") word.startsWith ("wh")
word.startsWith ("pr")
word.startsWith ("wr") )
38Using the Scanner Class
Enter a sentence (no punctuation) Now is the
time for all good people to translate this
sentence That sentence in Pig Latin is owNay
isyay ethay imetay orfay allyay oodgay eoplepay
otay anslatetray isthay en tencesay Translate
another sentence (y/n)?
39Summary
- Create and manipulate String objects
- Create and manipulate StringBuffer objects
- Create and manipulate Character objects (not the
primitive data type) - Use the StingTokenizer object to break Strings
into tokens - Use the Scanner class as a tokenizer