Strings - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Strings

Description:

Strings Mr. Smith AP Computer Science A – PowerPoint PPT presentation

Number of Views:152
Avg rating:3.0/5.0
Slides: 22
Provided by: WendyB194
Category:

less

Transcript and Presenter's Notes

Title: Strings


1
Strings
Mr. Smith AP Computer Science A
2
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 ()

3
Signatures of UsefulString 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)
4
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 ""
  • int msgLen msg.length()
  • int strLen str.length()

msgLen has a value of 13
strLen has a value of 0
Java Concepts 4.6 (Strings)
5
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
  • Examples
  • String msg "Hello, World!", str1, str2
  • String str1 msg.substring(0, 5)
  • String str2 msg.substring(7, 12)

H e l l o , W o r l
d !
Position 0 1 2 3 4 5 6 7
8 9 10 11 12
str1 has a value of "Hello"
str2 has a value of "World"
Java Concepts 4.6 (Strings)
6
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
  • Examples
  • String msg "Hello, World!", str1, str2
  • String str1 msg.substring(12)
  • String str2 msg.substring(7)

H e l l o , W o r l
d !
Position 0 1 2 3 4 5 6 7
8 9 10 11 12
str1 has a value of "!"
str2 has a value of "World!"
Java Concepts 4.6 (Strings)
7
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
  • Examples
  • String msg "Hello, World!"
  • int pos1 msg.indexOf("or")
  • int pos2 msg.indexOf("x")

H e l l o , W o r l
d !
Position 0 1 2 3 4 5 6 7
8 9 10 11 12
pos1 has a value of 8
pos2 has a value of -1
Java Concepts 4.6 (Strings)
8
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))
  • if (originalStr.equals(str2))
  • if (originalStr.equalsIgnoreCase(str2))

false
false
true
Java Concepts 5.2.3 (Comparing Strings)
9
Lets 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
  • What is the length of myTeam ?
  • stringLength myTeam.length()
  • What is the position of the first occurrence of
    "n" in myTeam ?
  • stringPos myTeam.indexOf("n")
  • What are the first 3 characters of myTeam ?
  • answer myTeam.substring(0, 3)
  • If myTeam equals myTeamLower, print They are
    equal.
  • if ( myTeam.equals(myTeamLower) )
  • System.out.println(They are equal)

stringLength contains 17
stringPos has a value of 6
answer has a value of Car
false, nothing prints
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
10
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 ).
  • 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

0123
11
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)
12
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)
  • int stringCompare2 str1.compareTo(str2)
  • int stringCompare3 originalStr.compareTo(Don")
  • int stringCompare4 originalStr.compareTo("1car")
  • If these 5 strings are sorted 1car, Don, car,
    cargo, casting

stringCompare1 is lt 0
stringCompare2 is lt 0
stringCompare3 is gt 0
stringCompare4 is gt 0
Java Concepts 5.2.3 (Comparing Strings)
13
String methods
on AP exam

Java Concepts Appendix C (pg. 643)
14
String methods

Java Concepts Appendix C (pg. 643)
15
String methods

Java Concepts Appendix C (pg. 643)
16
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)
17
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(endPosition1)
Java Concepts 4.6 (Strings), Appendix C (pg. 643)
18
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)
19
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)
20
Lets 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
  • Is myTeam less than myTeamLower ?
  • if (myTeam.compareTo(myTeamLower) lt 0)
  • Convert interestRateStr to a floating point
    number so that it can be used in a calculation.
  • interestRate Double.parseDouble(interestRateSt
    r)
  • 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)
21
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.showInput
    Dialog 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 dont pay off this credit card
    purchase after the first month.
  • Print the following information to the console
  • You purchased ltdescription of itemgt for ltamount
    of purchasegt dollars.
  • Your monthly interest rate is ltmonthly interest
    rategt .
  • You will be charged ltinterest amountgt in interest
    after the first month.
  • Test with a few scenarios and print out your code
    and the results
Write a Comment
User Comments (0)
About PowerShow.com