Title: Lecture 20: More on Strings
1Lecture 20 More on Strings
2Graphics vs Text
- Weve spent a lot of time doing graphics
- Wrote some fun games
- learned the basics of programming
- There are a lot of practical programs that arent
graphical - Word Processors
- IDEs like Eclipse (its kind of a combination)
- Your Java Compiler
- Lots of scientific programs just output text
3Strings
- Weve dealt with at least four classes for
dealing with text - Text
- an objectdraw object, draws some text on the
screen, allows it to be moved around - JTextField
- a GUI object lets the user enter some text in a
box - Jlabel
- object for displaying small amount of text in
GUIs - String
- This is the most basic Java Object for dealing
with text
String string This is a String
4What are Strings?
- String is a class in Java
- we know this already
- Behaves slightly differently from other objects
- Most types in Java are in one of 2 categories
- Object types
- Described by a class somewhere
- Created using a constructor and the new command
- Manipulated by calling methods
- Base types (int, boolean, double, etc)
- You can write literals
- 8, false, true, 45.98
- You can manipulate them with operators
- , -, , /, , , , etc.
5How have we used Strings?
- Define variables of type String
- Can assign values to String variables
- Can define functions that have String parameters
or return types. - Can specify String literals by writing things in
quotes - Can concatenate (connect) Strings with the
operator - Can determine if two Strings are equal using the
equals() method - Remember that we use equals(), not , with
Strings
String string text.getText()
text.setText(This is some text.)
String string Your Mom
if (selectedItem.equals(Blue)) //do
something
6So what type is String?
- Its an object, but Java has special support
built in, to make dealing with Strings easier - Can use literals, like base types
- Can use operators, like base types
- Can use constructors, like object types
- Can use methods on Strings, like objects
- There are 50 methods in the String class.
7Whats inside Strings?
- Strings are made up of characters
- It turns out, inside Strings are arrays of
characters - Strings are kind of like the collection classes
youre writing in Simon! - Instead of NoisyButtons, they have characters
- New base type char
- A char is a single character
- Can declare variables of type char
- Can write literals with single quotes
8The char type
- Declaring a char variable
- Just use char as the type
- Writing a char literal
- Use single quotes around one character
private char letter
letter T
9The char type
- Computers represent characters as numbers
internally - This is mostly hidden from the user
- There are lots of different encodings that
characters can be stored in - ASCII
- 256 characters
- American Standard for Computer Information
Interchange - Unicode
- Up to 65,536 characters
- About 35,000 are in use
- First 256 are same as ASCII
- Supports lots of languages (Chinese, Japanese,
etc) - Other encodings
- There are tons for Japanese, all different, huge
pain - ISO-2022JP, EUC, Shift-JIS, JIS, etc.
- Encodings just determine what numbers (codes)
represent particular characters on a computer - Or, you could say that an encoding is a way for a
computer to interpret some numbers known to be
characters.
10ASCII
- Below are the numbers representing different
ASCII characters
0 nul 1 soh 2 stx 3 etx 4 eot
5 enq 6 ack 7 bel 8 bs 9 ht
10 nl 11 vt 12 np 13 cr 14 so 15
si 16 dle 17 dc1 18 dc2 19 dc3 20
dc4 21 nak 22 syn 23 etb 24 can 25
em 26 sub 27 esc 28 fs 29 gs 30 rs
31 us 32 sp 33 ! 34 " 35
36 37 38 39 ' 40 (
41 ) 42 43 44 , 45 - 46
. 47 / 48 0 49 1 50 2 51 3
52 4 53 5 54 6 55 7 56 8
57 9 58 59 60 lt 61 62
gt 63 ? 64 _at_ 65 A 66 B 67 C
68 D 69 E 70 F 71 G 72 H
73 I 74 J 75 K 76 L 77 M 78
N 79 O 80 P 81 Q 82 R 83 S
84 T 85 U 86 V 87 W 88 X
89 Y 90 Z 91 92 \ 93 94
95 _ 96 97 a 98 b 99 c
100 d 101 e 102 f 103 g 104 h
105 i 106 j 107 k 108 l 109 m 110
n 111 o 112 p 113 q 114 r 115 s
116 t 117 u 118 v 119 w 120 x
121 y 122 z 123 124 125 126
127 del
11Comparing Characters
- Most encodings guarantee that charaters appear in
order - So you can compare them with operators like ints
- lt, gt, lt, gt, , and !
- Youre guaranteed that
- Uppercase letters are in alphabetical order
- So Z gt A
- Lowercase letters are in alphabetical order
- So z gt a
- Numbers are in numerical order
- So 9 gt 0, just like with numbers
12Getting characters from Strings
- You can get characters at particular indices in
Strings - Kind of like getting things from arrays
- Instead of , we use the charAt() method
- You can get the length of a String with the
length() method. - This returns the number of characters in the
String - Use these to iterate over all chars in a String
char c someString.charAt(5)
for (int i0 i lt someString.length() i)
char c someString.charAt(5) //do something
with c
13Checking Strings
- Suppose you had a program that took some input
- Say you have some JTextFields you want to only be
numbers - You can check this usng charAt().
- Heres a method to check that a String represents
a valid number - Can use this to tell if a String will be
converted properly to a number.
// Checks whether a given string can be
interpreted as an integer i.e., // checks
that it is made up of characters that are digits
in the range // 0-9. Returns true if and
only if the string can be interpreted as //
an integer. private boolean isInteger(String
aString) boolean allNumeric true
for (int i 0 (i lt aString.length()
allNumeric) i) if
(aString.charAt(i) lt '0' aString.charAt(i) gt
'9') allNumeric false
return allNumeric
14String methods
- Well go through some of the String methods
- You can use these in your program to search
through Strings in useful ways - This is probably the kind of stuff we would have
done first if this course werent mostly graphical
15indexOf()
- indexOf() returns the starting index of the first
occurrence of s in the String its called on - It returns -1 if it wasnt found
- Theres another version
- This will start searching at the index provided
public int indexOf(String s)
String courseName "Data Structures" int
position courseName.indexOf(r)
public int indexOf(String s, int start)
16indexOf()
- Whats the result of each of these?
String courseName "Data Structures"
courseName.indexOf("Struct", 2)
courseName.indexOf("Struct", 8)
courseName.indexOf("t", 2)
courseName.indexOf("t", 6)
courseName.indexOf("t", 7)
17Counting words
- You could write a method that counts the number
of times a particular word occurs in a String - What does this return for these calls?
public int wordCount(String text, String
word) int count 0 int pos
text.indexOf(word,0) while (pos gt 0)
count pos
text.indexOf(word,posword.length())
return count
wordCount("yabbadabbadoo","abba") wordCount("scoo
bydoobydoo","oo")
18Counting words
- You could write a method that counts the number
of times a particular word occurs in a String - How about this one?
- How would you modify this to get all of the
bobs?
public int wordCount(String text, String
word) int count 0 int pos
text.indexOf(word,0) while (pos gt 0)
count pos
text.indexOf(word,posword.length())
return count
wordCount("bubbabobobbrain","bob")
19Case-insensitivity
- You can use two methods in Java to convert
Strings to upper or lowercase - So you could modify our previous method to count
words regardless of case by adding just two lines
public String toLowerCase() public String
toUpperCase()
private int substringCounter( String text,
String word) int count 0
text text.toLowerCase() word
word.toLowerCase() int pos
text.indexOf(word,0) while (
pos gt 0 ) count pos
text.indexOf(word,posword.length())
return count
20Immutability
- Note that in that method, we had to assign the
result of toUpperCase() and toLowerCase() to the
variables - Java Strings are immutable
- You cant change them with methods
- You can only make new Strings and assign them
back to the variables - Thats what these methods are doing.
private int substringCounter( String text,
String word) int count 0
text text.toLowerCase() word
word.toLowerCase() //etc.
21Cutting Strings up
- You already know we can put Strings together
using the operator - If you want to take Strings apart, use the
substring() method - For example, this will put 2 Strikes in
strikesOnly
public String substring(int startIndex, int
indexBeyond)
String countText "3 Balls, 2 Strikes, 2
Outs" String strikesOnly strikesOnly
countText.substring(9,18)
22Some more String methods
public boolean startsWith(String s) //
true only if this string starts with s
public boolean endsWith(String s)
// true only if this string ends with s
public boolean equals(String s) // true
only if this string has same sequence of chars as
s public boolean
equalsIgnoreCase(String s) // true only
if this string has same sequence of chars as s
// except capital lower case letters
considered the same
23Some more String methods
public int lastIndexOf(String s) public
int lastIndexOf(String s, int startIndex)
// return index of last occurrence of s
(occurring at or // before
startIndex) in this string, and -1 if no match.
public String replace(char oldChar, char
newChar) // Returns a new string
resulting from replacing all //
occurrences of oldChar in this string with
newChar. public String trim()
// Eliminates all leading and trailing spaces.
public int compareTo(String s)
// Returns negative int if string before s
in case-sensitive // dictionary
order // returns 0 if equal
// returns positive int if string after s in
case-sensitive // dictionary
order. public char charAt(int index)
// Returns the character at the specified
index.