faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/Java/StringsAndHelper... · Web viewStrings...
Transcript of faculty.cse.tamu.edufaculty.cse.tamu.edu/slupoli/notes/Java/StringsAndHelper... · Web viewStrings...
Strings and a Helper Class
Some basics on Strings
· Strings can be ONE or more characters of text strung together
· “c” is a string
· “Mr. Lupoli stinks” is a string
· “123-213-1232” is a string
· “123123123” is a string
· Strings are immutable!!!
· If we make ANY changes we have to use the “=”
· A character data type cannot be a String
· To create a string
· notice when using Strings “” are used
· CHARACTERS use ‘ ’, you cannot use “”
String name = “Lupoli”;
String two = name; // equals is not just used for math
Index(ices)
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
L
u
p
o
l
i
name
// notice a String starts at index 0!!
String Declaration and Initialization
· Sets aside an array of elements
· each element contains a String (single letter)
· Assigning values
· Must use “ “’s to set if literal
· variable = sc.next(); only reads up to the first white space.
· variable = sc.nextLine(); reads the whole line typed.
· don’t have to worry about declaring a SIZE that fits!! (automatically done!!)
· can use = to set a String
· can use + to concatenate
· No special treatment, just like any other variable
· MUST GIVE A DEFAULT VALUE!!! (“”)
String Declaration and Initialization
Gathering values into Strings Example 1
String firstName = “”, lastName = “”;
firstName = sc.next (); // input: Mr. Lupoli
lastName = sc.next ();
System.out.print(lastName + “, “ + firstName); // output: Lupoli, Mr.
firstName
lastName
0
1
2
M
r
.
0
1
2
3
4
5
L
u
p
o
l
i
Gathering values into Strings Example 2
String firstName = “Kristen”;
String lastName = “Davis”;
System.out.print(lastName + “, “ + firstName); // output: Davis, Kristen
firstName
lastName
K
r
i
s
t
e
n
D
a
v
i
s
Gathering values into Strings Example 3
String wholeName = “”;
wholeName = sc.nextLine(); // input: Mr. Lupoli
System.out.print(wholeName); // output: Lupoli, Mr.
wholename
0
1
2
3
4
5
6
7
8
9
M
r
.
L
u
p
o
l
i
String as an Object
· a String is much more complicated than we know
· a String is an OBJECT (class)
· has helper function that give it more features
· treated as it’s OWN powerful identity
The OBJECT String
String as you know it
String as it really is
Code
Display/Result
String name = "Lupoli";
System.out.println(name.charAt(0));
System.out.println(name.length());
L
6
What is a helper function?
· a pre-created code to help with mundane tasks
· gives the objects more features
· to use
· name of the variable “dot” helper function name
· many functions are used over and over again, why recreate the wheel!!
How to identify and read Helper functions
· API’s given by Java show all helper functions available
· Application Programming Interface
· think of it as a dictionary or directory
· API’s for Strings (Java 6)
· http://java.sun.com/javase/6/docs/api/java/lang/String.html
· General APIs
· http://java.sun.com/javase/6/docs/api/
API listing breakdown
Method Summary
char charAt(int index) Returns the char value at the specified index.
what datatype the function gives back (returns) when called
name of function
what function needs in order to work (called a parameter)
Exploring what String Helper functions do
· use the code I give you below, and call the functions listed below
· see what displays
Use this code for exercise
public class helloWorld
{
public static void main(String[] args)
{
String name = "Lupoli";
System.out.println(name.charAt(0));
// Place all code for below here
}
} // may have to change the class name to match the file name
// complete the functions below on the code above to determine the output
function
code
Output
Datatype returned?
charAt
System.out.println(name.charAt(0));
L
char
isEmpty()
toLowerCase()
toUpperCase()
indexOf(String str)
System.out.println(name.indexOf(“p”));
System.out.println(name.indexOf(“Z”));
DOUBLE QUOTES WILL BE OFF
Revisiting the ASCII Table
· alphabetical/numerical work just fine
· but mixing the two proves more interesting
· uses the ASCII table (covered in strings)
0 – 9 A – Z a – z
What value is A, a, Z and z respectfully?
What is the answer to below?
L u p o l i
76 117 112 111 108 105
Lupoli (<, >, ==) Luppold
Comparing Strings (more helper functions)
· normal comparison symbols do not work!!
· == , <=, >=, !=, >, <. etc…
· because String is a COMPLEX datatype
· compareTo
· compares two strings
· method returns a value
· == 0 (match)
· < 0 no match, S1 is alphabetically less than S2
· > 0 no match, S1 is alphabetically greater than S2
· equals (boolean)
· answer if an EXACT match
· compareToIgnoreCase/equalsIgnoreCase
· ignore case of strings, works the same way
// what is IgnoreCase??
Calling String helper function
· Same format each time
· Values returned can be placed in variables!!
(name of the string).(helper function)
Example String Helper Function Calls
int space = comment.indexOf(“ “);
String name = comment.substring(10);
String newLine = comment.replace(“Lupoli”, “Dork”);
Values compareTo( ) returns
String x = “cat”;
String y = “dog”;
x.compareTo(y);
returns
when
< 0
string1 alphabetically/ASCII before string2
cat dog
0
string1 alphabetically/ASCII INDENTICAL string2
cat cat
> 0
string1 alphabetically/ASCII” after string2
dog cat
compareTo in use
// compareTo example
String testOne = "Lupoli";
String testTwo = "Martino";
if(testOne.compareTo(testTwo) < 0)
{ System.out.println("testOne is LESS than testTwo"); }
else if(testOne.compareTo(testTwo) > 0)
{ System.out.println("testOne is GREATER than testTwo"); }
else // (testOne.compareTo(testTwo) == 0)
{ System.out.println("testOne is EQUAL to testTwo");}
if(testOne.compareTo("Lupoli") == 0)
{ System.out.print("Strings matched"); }
Values equals( ) returns
String x = “cat”;
String y = “dog”;
if( x.equals(y) ) // usually inside an IF statement
returns
when
0 (false)
string1 alphabetically/ASCII NOT IDENTICAL string2
1 (true)
string1 alphabetically/ASCII IDENTICAL string2
equal
// equal example
testOne = "Lupoli";
testTwo = "Martino";
if(testOne.equals(testTwo))
{ System.out.println("testOne is LESS than testTwo"); }
else // (testOne.equals(testTwo) == 0)
{ System.out.println("testOne is EQUAL than testTwo"); }
if(testOne.equals("Lupoli"))
{ System.out.println("Strings matched"); }
String comparing exercise
String 1 (x)
String 2 (y)
comparison
Answer
cat
dog
x.equals(y)
false
Lupoli
Luppold
x.compareTo(y)
Zach
Emily
x.compareTo(y)
Eric
Eric
x.compareTo(y)
Mandy
MANDY
x.equals(y)
Mandy
MANDY
x.equalsIgnoreCase(y)
So… Strings are immutable, so what??
· Remember Strings are immutable
Non-immutable strings example
public class Example {
public static void main(String[] args) {
String answer = "Lupoli";
// trying to add something WITHOUT resetting the string
answer.concat(" is awesome");
System.out.println("And we now have: " + answer);
// trying to add something WITH resetting the string
answer = answer + " stinks";
System.out.println("And we now have: " + answer);
}
}
And we now have: Lupoli
And we now have: Lupoli stinks
· We now have StringBuilder
· Strings that are mutable
· http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Editing elements in a String array
· HAVE TO DELCARE THE STRING FIRST!!!
· individual characters inside a String array can be accessed.
Accessing a value inside an String
String fname = “John”;
System.out.print(“Character at index 2 is “ + fname[2] + “\n”); // displays ‘h’
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
J
o
h
n
\0
Editing a value inside a String
String fname = "John";
fname = fname.replace('h', 'X'); // editing element number 2, NOTICE NO CHAR!!
System.out.print("Name: " + fname + "\n"); // displays “JoXn”
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
J
o
X
n
\0
FYI another way:
result = 't' + result.substring(1,result.length())
Finding a “null” or “” in a String/array of Strings
· you might find that an array element does not contain viable data
· to find, use the “.equals()” string command
· commonly mistaken what to do
Common search errors
String
String in an Array
if(answers[i] != "") { length++; }
if(answers[i] != " ") { length++; } if(answers[i] != null) { length++; }
if(answers[i] != "null") { length++; }
Correct null search code
String
String in an Array
String type = “”;
if(answers.equals(""))
if(!answers[i].equals("") ) { length++; }
Concatenation
· adds to END of existing String
· the string will increase in size automatically
· syntax
· final = original + attachment;
· final = original.concat(attachment);
· concat will ONLY work with Strings (not ints)
Code
Visually
String string1 = “Goodbye”;
String string2 = “, Cruel ”;
string1 = string1 + string2;
string1 = string1 + “World!”; // literal string
string1
G
o
o
d
b
y
e
string1
G
o
o
d
b
y
e
,
_
C
r
u
e
l
_
string1
G
o
o
d
b
y
e
,
C
r
u
e
l
W
o
r
l
d
!
Determine what “answer” will look like after the code below WITHOUT A COMPILER!!! Draw it out!!!
1. String string1 = “Goodbye”; // drawn below
2. String string2 = “, Cruel ”;
3. String answer = “”;
4. answer = answer + string1;
5. answer += string2; // hmmm, think about it!!
6. string1 = “Lupoli”;
7. answer = answer + string1;
8. System.out.println(answer); // put answer below (if not already!)
string1
string2
answer
Search Methods
contains methods
returns
method
boolean
contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values.
String line = "Mr. Lupoli is a programming professor";
if(line.contains("Lupoli") || line.contains("LUPOLI"))
{ System.out.println("Yeah, he's in there"); }
else
{ System.out.println("Nope, not in there"); }
String variable = "Munson";
if(line.contains(variable))
{ System.out.println("Yeah, he's in there"); }
lastIndexOf method
int
lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.
int
lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
int
indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.
String line = "Mr. Lupoli is a programmer professor";
1. What direction will the search start?
2. What datatypes will these functions below return??
3. What are these functions returning in general?
4. Determine what each display will produce System.out.println(line.lastIndexOf("pro"));
System.out.println(line.lastIndexOf('o'));
System.out.println(line.lastIndexOf('o', 20));
substring methods
String
substring(int beginIndex) Returns a new string that is a substring of this string.
String
substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
String line = "Mr. Lupoli is a programming professor";
// Determine what each display will produce
String subString1 = line.substring(4);
System.out.println(subString1);
String subString2 = line.substring(4, 9);
System.out.println(subString2);
Converting a number to a Stringint value = 27;
String greeting = “Hello There”;
H
e
l
l
o
T
h
e
r
e
String complete = greeting + value; // just the same as concatenation of 2 Strings!!
H
e
l
l
o
T
h
e
r
e
2
7
Converting Strings to Numbers - FYI
There will be many times were the input interface will treat whatever the user types in as a String, (JOptionPane), we can then transform that input into the format intended.
String x;
int real_number;
realnumber = Integer.parseInt(x); // now “realnumber” is actually an INT value 23
Type Name
Method for conversion
byte
Byte.parseByte(String_to_convert)
short
Short.parseShort(String_to_convert)
int
Integer.parseInt(String_to_convert)
long
Long.parseLong(String_to_convert)
float
Float.parseFloat(String_to_convert)
double
Double.parseDouble(String_to_convert)
// x = JOptionPane.showDialog(“Enter a whole number:”); // “x” is a STRING 23
Helper Method - Char at (charAt)
· returns a CHAR value from a specific AND single location in the string
· great for grabbing the FIRST letter of a first name for a username
· usually in if statements and for loops
· great for counting spaces
charAt() function
Returns
Syntax
char
charAt(int index) Returns the char value at the specified index.
name
J
o
n
a
t
h
o
n
P
h
i
l
l
i
p
s
int frequency = 0;
for(int i = 0; i < name.length(); i++)
{
if(name.charAt(i) == ' ') { frequency++; }
} // counts # of spaces in the name
String Tokenizer
· import java.util.StringTokenizer;
· breaks input line into a sequence of Strings (words) separated by spaces
· CANNOT TOKENIZE INDIVIDUAL LETTERS (use .charAt( ))
· this String below was read in using sc.readLine( );
M
r
.
L
u
p
o
l
i
i
s
d
a
b
o
m
b
tokens
(separated by spaces)
String inputline = sc.nextLine( );
StringTokenizer tokenizer = new StringTokenizer(inputline);
Other tokenize functions
tokenizer.hasMoreTokens( );
· determines if more “tokens” in the String
· used usually in a conditional loop
String word = tokenizer.nextToken( );
· grabs next token, assigns to “word”
· records last place it grabbed a word
int count = tokenizer.countTokens( );
returns the number of tokens remaining to be returned by NEXTTOKEN()
Introduction to the While Loop
· Condition is tested BEFORE body of the loop
· used when NOT sure when it may end
· need a priming read to test condition before it will loop
· priming read, ask for a value, tests the answer with the loop condition
While Loop Structure
Flowchart Example
1
Yes
Inside loop body
5
4
2
3
No
Continue outside of loop body
While Loop
While loop Example
// import Scanner!!
Scanner sc = new Scanner(System.in);
public static void main(String args[]){ int getValue, setTotal;
/* Give directions to user */ System.out.print( “This program adds a list of numbers.\n”); System.out.print( “Signal end of list with a 0.\n”);
setTotal = 0; /* Initialize setTotal */
/* Get integers from the user until a 0 is entered */
// Get the first integer from the user
// This is known as a "priming read" */
System.out.print( “Enter an integer, 0 to end : \n”);
getValue = sc.nextInt();
// Continue to get integers from the user
// until a 0 is entered, accumulating into setTotal
while (getValue != 0)
{
setTotal = setTotal + getValue; // running setTotal
System.out.print( “Enter an integer, 0 to end : \n”);
getValue = sc.nextInt();
}
/* Print the total */ System.out.print( “The total is “ + setTotal + “\n”);}
T
h
a
n
k
y
o
u
v
e
r
y
m
u
c
h
!
Scanner sc = new Scanner(System.in);
String inputline = sc.nextLine( ); // user inputted line above
StringTokenizer tokenizer = new StringTokenizer(inputline);
Use the loop to grab each token from the string and display each token. Some of the answer is given below. Loop at the Java API for StringTokenizer (or Tokenizer functions above) to see if there is a way to determine IF there are no tokens left!!
while( )
{
System.out.println( );
}
Array of Strings
String [] nameOfDay = { // Array of 7 string
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
Sunday Tuesday Thursday Saturday
0 1 2 3 4 5 6
Monday Wednesday Friday
System.out.println(nameOfDay[5]); // displays “Friday”
Breaking down a String
· you can look at individual chars inside a string
· use the char functions to determine what is inside that string
· isLetter
· isDigit
· isWhitespace
· isLowerCase
· isUpperCase
String line = “Goodbye, Cruel World”;
G
o
o
d
b
y
e
,
C
r
u
e
l
W
o
r
l
d
!
\0
√
√
√
√
√
√
√
√
√
√
√
√
√
√
√
√
√
Total = 17
Is Upper Letter example
int count = 0;
for(int i = 0; i < line.length(); i++) // counts # of letters in the string
{
if(Character.isUpperCase(line.charAt(i))){ count++; }
}
System.out.println(count);
isDigit example
int count = 0;
for(int i = 0; i < line.length(); i++) // counts # of numbers in the string
{
if(Character.isDigit(line.charAt(i))){ count++; }
}
System.out.println(count);
1. Assign helper functions to teams
2. Have them look up how to use the functions (find examples on google)
a. simple examples!! You will find crazy ones
3. Test example by coding it in Eclipse (copy paste, adjust slightly)
4. Create a new example using the function degrading Lupoli
String start = “Lupoli needs a vacation”;
String answer = start.replace(‘i’, ‘ ‘);
System.out.println(answer);
5. Draw what the function is doing in an animation/cartoon
a. make sure to explain, BUT NOT IN SENTENCES!!
b. use markers to draw
c. use the entire paper, make it as big as you can!
i. yes, we can try, try again
d. place name in lower right corner (small)
e. please be neat
f. be creative!!!
g. check with Mr. Hughes or Mr. Lupoli when completed
6. Will combine into ONE document so all can use!!!
20