Download Strings

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Strings
Mr. Smith
AP Computer Science A
What are Strings?
Name some of the characteristics of
strings:





A string is a sequence of characters, such
as “Hello, World!”
Strings are objects
Strings are sent messages
Strings do not need to be instantiated
Strings can be combined using the
concatenation operator (+)
Signatures of Useful
String Methods

int length()
 returns the length of the string

String substring(int start, int end)
 returns the substring beginning at start and ending at (end – 1)

String substring(int start)
 returns the substring beginning at start and ending at the end of the string

int indexOf(String otherString)
 returns the index of the first occurrence of otherString
 returns -1 if str is not found

boolean equals(String otherString)
 Compares string to otherString. Returns true if equal (otherwise false).
 Never test for string equality by using ==
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
length
int length()




Returns the length of a string
This is a count of the number of characters
in the string, including spaces
A string with a length of 0 is called the
empty string
Examples:
String msg = "Hello, World!", str = "";
msgLen has a value of 13
int msgLen = msg.length();
strLen has a value of 0
int strLen = str.length();
Java Concepts 4.6 (Strings)
substring
String substring(int start, int end)



Returns a substring of the string
The substring is composed of the characters
beginning at position start and ending at position
(end – 1). In other words, you tell it the position
of the first character you want and the position of
the first character you do not want.
The first position of the string is always position 0
H e l
Position: 0

1
2
l
o
,
3
4
5
W o r
6
7
8
l
d !
9 10 11 12
Examples:
String msg = "Hello, World!", str1, str2;
String str1 = msg.substring(0, 5);
str1 has a value of "Hello"
String str2 = msg.substring(7, 12);
str2 has a value of "World"
Java Concepts 4.6 (Strings)
substring
String substring(int start)


Returns a substring of the string
The substring is composed of the characters
beginning at position start and ending at the end
of the string
H e l
Position: 0

1
2
l
o
,
3
4
5
W o r
6
7
8
l
d !
9 10 11 12
Examples:
String msg = "Hello, World!", str1, str2;
String str1 = msg.substring(12); str1 has a value of "!"
String str2 = msg.substring(7);
str2 has a value of "World!"
Java Concepts 4.6 (Strings)
indexOf
int indexOf(String otherString)


Returns the position of the first occurrence of
otherString in the string
Returns -1 if otherString is not found in the string
H e l
Position: 0

1
2
l
o
,
3
4
5
W o r
6
7
8
Examples:
String msg = "Hello, World!";
int pos1 = msg.indexOf("or");
int pos2 = msg.indexOf("x");
l
d !
9 10 11 12
pos1 has a value of 8
pos2 has a value of -1
Java Concepts 4.6 (Strings)
equals
boolean equals(String otherString)




Returns true if the string equals otherString or
returns false if they are not equal
The comparison is case sensitive. Note: you
should use equalsIgnoreCase(String otherString)
if you want to ignore case during the comparison.
Do not use == to compare strings. This will
usually not return the desired result
Examples:
String originalStr = "North", str1 = "South", str2 = "north";
if (originalStr.equals(str1))
false
false
if (originalStr.equals(str2))
trueJava Concepts 5.2.3 (Comparing Strings)
if (originalStr.equalsIgnoreCase(str2))
Let’s try out these
String methods
String myTeam = “Carolina Panthers”;
String myTeamLower = “carolina panthers”;
String answer;
int stringLength, stringPos, stringCompare;
Write the Java code to answer the following questions:
1.
2.
3.
4.
What is the length of myTeam ?
stringLength contains 17
stringLength = myTeam.length();
What is the position of the first occurrence of "n" in myTeam ?
stringPos = myTeam.indexOf("n"); stringPos has a value of 6
What are the first 3 characters of myTeam ?
answer = myTeam.substring(0, 3); answer has a value of “Car”
If myTeam equals myTeamLower, print “They are equal”.
if ( myTeam.equals(myTeamLower) ) false, nothing prints
System.out.println(“They are equal”);
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
StringCompare
Write a StringCompare and StringCompareViewer class to:



Have the user input a sentence to the console or into an input dialog window.
Also, have the user input a search value (could be one character, several
characters, or a phrase) to the console or into an input dialog window. We will
name this searchValue.
Your program print the following to the console:
 Print both the sentence and the searchValue strings
 Print the length of both the sentence and the searchValue strings
 Find the first occurrence of searchValue in the sentence and print out the
position in sentence where it is found (i.e. if sentence has a value of
“Carolina Panthers” and searchValue has a value of “ol”, then you should print 3 ).
0123
 Compare sentence to searchValue and determine if they are equal. Print out a
sentence stating whether they are equal or not.
 Print the first word in the sentence string.

Extra credit (worth 2 points each):
 Determine the number of words in sentence and print this number to the console.
Note that words are separated by a space. Use a while loop.
 Determine the number of occurrences of searchValue in sentence and print it to the
console (i.e. if sentence has a value of “Carolina Panthers are number one” and
searchValue has a value of “n”, then you should print 4 ). Use a while loop.

Remember to test with a few scenarios to make sure that it works
compareTo
int compareTo(String otherString)


Compares the original string to otherString to see how they
alphabetically compare. The comparison is case sensitive.
The “dictionary” ordering used by Java is slightly different than a
normal dictionary. Java is case sensitive and sorts in this order
(lowest to highest):
S N U L (lowest
highest)





Space and special characters come before other characters
Numbers are sorted after the space character
Uppercase characters are sorted next
Lowercase characters are sorted after that
When Java compares two strings, corresponding letters are
compared until one of the strings ends or a difference is
encountered. If one of the strings ends, the longer string is
considered the later (greater) one.
Java Concepts 5.2.3 (Comparing Strings)
compareTo
int compareTo(String otherString) - continued




If the two strings are equal it returns 0.
If the original string is less than otherString, it returns
a value less than 0.
If the original string is greater than otherString, it
returns a value greater than 0.
Examples:
String originalStr = "car", str1 = "cargo", str2 = “casting";
int stringCompare1 = originalStr.compareTo(str1); stringCompare1 is < 0
stringCompare2 is < 0
int stringCompare2 = str1.compareTo(str2);
int stringCompare3 = originalStr.compareTo(“Don"); stringCompare3 is > 0
int stringCompare4 = originalStr.compareTo("1car"); stringCompare4 is > 0
If these 5 strings are sorted: 1car, Don, car, cargo, casting
Java Concepts 5.2.3 (Comparing Strings)
String methods
*** on AP exam
***
***
Java Concepts Appendix C (pg. 643)
String methods
***
***
***
Java Concepts Appendix C (pg. 643)
String methods
***
Java Concepts Appendix C (pg. 643)
Advanced
Operations on Strings



Consider the problem of extracting words
from a line of text.
To obtain the first word, we could find the
first space character in the string (assuming
the delimiter between words is the space)
or we reach the length of the string.
Here is a code segment that uses this
strategy:
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
Advanced
Operations on Strings

The problem is solved by using two separate String
methods that are designed for these tasks.
String original = "Hi there!";
// Search for the position of the first space
int endPosition = original.indexOf(" ");
// If there is no space, use the whole string
if (endPosition == -1)
endPosition = original.length();
// Extract the first word
String word = original.substring(0, endPosition);
// Extract the remaining words of the string
String remainingWords = original.substring(endPosition+1);
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
Integer.parseInt
int Integer.parseInt(String str)




Use the static method parseInt of the Integer
class to convert a string to an integer
This is helpful when prompting a user in an
input dialog window for an integer
The string must be an integer or the program
will throw a NumberFormatException error.
Examples:
String cash = “20";
int dollarAmt = Integer.parseInt(cash);
Java Concepts 4.6 (Strings)
Double.parseDouble
double Double.parseDouble(String str)




Use the static method parseDouble of the Double
class to convert a string to a floating point number
This is helpful when prompting a user in an input
dialog window for a floating point number
The string must be an floating point number or an
integer or the program will throw a
NumberFormatException error.
Examples:
String cash = "19.75";
double cashAmt = Double.parseDouble(cash);
double dollarAmt = Double.parseDouble("20");
Java Concepts 4.6 (Strings)
Let’s try out these
String methods
String myTeam = “Carolina Panthers”;
String myTeamLower = “carolina panthers”;
String interestRateStr = “7.50”, ageStr = “18”;
int stringCompare, age;
double interestRate;
Write the Java code to perform the following:
1.
2.
3.
Is myTeam less than myTeamLower ?
if (myTeam.compareTo(myTeamLower) < 0)
Convert interestRateStr to a floating point number so that it can be
used in a calculation.
interestRate = Double.parseDouble(interestRateStr);
Convert ageStr to an integer so that it can be used in a calculation.
age = Integer.parseInt(ageStr);
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
InterestRate
Create an InterestRate class and InterestRateViewer client class to do
the following:




A person is purchasing an item with their credit card. Launch an input dialog
window and have the user enter a short description of the item they are
purchasing. Remember the JOptionPane.showInputDialog method that we used
in an earlier class?
Have the user input the amount of the purchase (in whole dollars – i.e.
integer) into an input dialog window.
Have the user input (into another input dialog window) the monthly interest
rate they are paying on this purchase. Note that this may include decimal
places (i.e. they would enter 5.75 to represent 5.75%).
Your program should take these values and do the following:
 Calculate the amount the user will be charged in interest if they don’t pay off this
credit card purchase after the first month.
 Print the following information to the console:
You purchased <description of item> for <amount of purchase> dollars.
Your monthly interest rate is <monthly interest rate> %.
You will be charged <interest amount> in interest after the first month.

Test with a few scenarios and print out your code and the results