Upload
blaise-gaines
View
225
Download
1
Embed Size (px)
Citation preview
CSCI 1302 – Strings 2
Outline
• Introduction• The String class
– Constructing a String– Immutable and Canonical Strings– String Length and Individual Characters– String Concatenation– Extracting Substrings– String Comparisons– String Conversions
CSCI 1302 – Strings 3
Outline– Finding a Character or a Substring– Conversions between Strings and Arrays– Converting Characters and Numeric
Values to Strings
• The Character Class• The StringBuffer Class
– Constructing a String Buffer– Modifying Strings in the Buffer– Important Methods
CSCI 1302 – Strings 4
Outline
• The StringTokenizer class• The Scanner class (JDK 1.5 feature)• Implementing MyInput Using Scanner • Command-Line Arguments
– Passing Strings to the main Method– Processing Command-Line Arguments
CSCI 1302 – Strings 5
Introduction
• Sequence of characters• Often represented as an array of
characters• Is an object in Java• String – efficient for storing and
processing• StringBuffer – used for flexible strings
that can be modified• StringTokenizer – utility class
CSCI 1302 – Strings 6
The String class
• Models a sequence of characters• Total of eleven constructors• Over forty methods for working with
strings• Methods include examining individual
characters in a sequence, comparing strings, searching substrings, extracting substrings, and creating a copy of a string with a change of case
CSCI 1302 – Strings 7
Constructing Strings
• Strings can be created from a string literal or an array of charactersString newString = new String(“Message”);
• Shorthand initializerString newString = “Message”;
• Array of characterschar[] charArray = {‘H’,’i’,’!’};String newString = new String(charArray);
CSCI 1302 – Strings 8
Immutable Strings
• A String object is immutable, its contents cannot be changed
String s = “Java”;s = “HTML”;
s: String
String object for "Java"
s
After executing String s = "Java";
After executing s = "HTML";
: String
String object for "Java"
s
s: String
String object for "HTML"
Contents cannot be changed
This string object is now unreferenced
CSCI 1302 – Strings 9
Canonical Strings
• JVM stores two String objects in the same object if they were created with the same string literal using shorthand initialization
• This is a canonical string• Use the intern() method to return the
canonical string
CSCI 1302 – Strings 10
Canonical Strings
s1 == s is false s2 == s is true s == s3 is true
String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s == s3 is " + (s == s3));
: String
Canonical string object for "Welcome to Java"
: String
A string object for "Welcome to Java"
CSCI 1302 – Strings 11
String Length
• Use length() to get length of a string
String message = “Java”;message.length(); // returns 4
CSCI 1302 – Strings 12
Individual Characters
• Use charAt(index) to retrieve a specific character
• Index starts at 0• Don’t use array index notation message[2]
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.charAt(0) message.charAt(14) message.length() is 15
CSCI 1302 – Strings 13
String Concatenation
• Use the concat(String s) method or the + symbol to concatenate two strings
String s1 = “Hello ”;String s2 = “World”;String s3 = s1.concat(s2);String s3 = s1 + s2;
Hello World
CSCI 1302 – Strings 14
Extracting Substrings
• Returns a substring of the original stringpublic String substring(int begin, int end);public String substring(int begin);
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.substring(0, 11) message.substring(11)
CSCI 1302 – Strings 15
String Comparisons
• Compare string contents with the equals(String s) method not ==
String s0 = “ Java”;String s1 = “Welcome to” + s0;String s2 = Welcome to Java”;
System.out.println(“s1==s2 is “ + (s1==s2)); // false
System.out.println(“s1.equals(s2) is “ + (s1.equals(s2))); // true
CSCI 1302 – Strings 16
String Comparisons
• Can also use the compareTo(String s) method
• Don’t use >, >=, <, or <=s1 = “abc”;s2 = “abg”;s3 = “abc”;s4 = “aba”;s1.compareTo(s2); // returns -4s1.compareTo(s3); // returns 0s1.compareTo(s4); // returns 2
CSCI 1302 – Strings 17
String Comparisons
• Use equalsIgnoreCase(String s) for case-insensitive equality
• Use the regionMatches method for comparing substrings
• Use startsWith(prefix) or endsWith(suffix) to check whether a string starts or ends with a certain substring
CSCI 1302 – Strings 18
String Conversions
• String contents cannot be changed, but new strings can be created and transformed with various methods
“Welcome”.toLowerCase(); // welcome“Welcome”.toUpperCase(); // WELCOME“ Welcome ”.trim(); // Welcome“Welcome”.replace(‘e’,’A’); // WAlcomA“Welcome”.replaceFirst(“e”,”A”); // WAlcome
“Welcome”.replaceAll(“e”,”A”) // WAlcomA
CSCI 1302 – Strings 19
String Conversions
• Use these methods to find the first or last (add last in front of each method name) occurrence of a character or substring in a given string
• All return -1 if it is not foundpublic int indexOf(int ch);public int indexOf(int ch, int from);public int indexOf(String str);public int indexOf(String str, int fromIndex);
CSCI 1302 – Strings 20
String ConversionsExamples
"Welcome to Java".indexOf('W') returns 0"Welcome to Java".indexOf('x') returns -1"Welcome to Java".indexOf('o', 5) returns 9"Welcome to Java".indexOf("come") returns 3"Welcome to Java".indexOf("Java", 5) returns 11
"Welcome to Java".indexOf("java", 5) returns -1
"Welcome to Java".lastIndexOf('a') returns 14
CSCI 1302 – Strings 21
Conversions between Strings and Arrays
• String to char Arraychar[] chars = “Java”.toCharArray();
• Use getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) to replace substringschar[] dst = {‘J’,’A’,’V’,’A’};“SAWS”.getChars(2,3,dst,2);
dst becomes {‘J’,’A’,’W’,’S’}
CSCI 1302 – Strings 22
Conversions between Strings and Arrays
• Convert array of characters into a stringString str = new String(new char[]{‘J’,’a’,’v’,’a’});String str = String.valueOf(new char[]{‘J’,’a’,’v’,’a’});
CSCI 1302 – Strings 23
Conversions between Strings and Arrays
• Convert other types to strings• Use overloaded versions of valueOf to
convert char, double, long, int, and float.
String str = new String.valueOf(5.44);String str = String.valueOf(3);
CSCI 1302 – Strings 24
Palindromes
• A word that is the same backwards and forwards
• Examples of palindromes:– Mom– Noon– Dad– Kayak– Racecar
• See TestPalindrome.java
CSCI 1302 – Strings 25
Primitive wrapper classes
• Java provides wrapper classes for the primitive types so they can be treated like objects
• All contained in the java.lang package• Helps process primitive values• Will go into more detail with other
primitive wrapper classes in Chapter 9
CSCI 1302 – Strings 26
The Character class
• One constructor, more than 30 methods• Most methods are static• Create a Character object
Character character = new Character(‘a’);
• Return a Character objectcharValue(‘a’);
• Compare Character objectscharacter.compareTo(‘a’);character.equals(‘a’);
CSCI 1302 – Strings 27
The StringBuffer class
• More flexible than String• Can add, insert, or append new
contents• Three constructors, over thirty methods• See Figure 7.8 on p.270 for common
methods
CSCI 1302 – Strings 28
Constructing StringBuffer
• Three constructors– public StringBuffer() – No characters,
initial capacity of sixteen characters– public StringBuffer(int length) – No
characters, initial capacity of length characters
– public StringBuffer(String s) – Constructs a string buffer with an initial capacity of sixteen plus the length of the string argument
CSCI 1302 – Strings 29
Modifying StringBuffers
• Can append new contents to the end of an existing buffer, insert new contents, or delete/replace characters
• Append charactersStringBuffer sb = new StringBuffer(“We”);sb.append(“lcome to Java”);
• Insert charactersStringBuffer sb = new StringBuffer(“As”);sb.insert(1,“ Welcome to Java”);
A Welcome to Javas
CSCI 1302 – Strings 30
Modifying StringBuffers
• Other useful methods
sb.delete(8, 11); // Welcome Javasb.deleteCharAt(8); // Welcome o Javasb.reverse() // avaJ ot emocleWsb.replace(11,15,”HTML”); // Welcome to HTML
sb.setCharAt(0,’w’); // welcome to Java
CSCI 1302 – Strings 31
Modifying StringBuffers• Other useful methods
– toString() – returns the string– capacity() – returns the capacity– length() – returns the number of
characters stored– setLength(newLength) – sets the length,
truncates or pads– charAt(index) – returns the character at
specified index (0-based)• See PalindromeIgnoreNonAlphanumeric.java
CSCI 1302 – Strings 32
The StringTokenizer class
• Allows you to process strings• Specify a set of delimiters• Each string “piece” is a token• Specify delimiters in constructors
CSCI 1302 – Strings 33
Constructing StringTokenizers
• public StringTokenizer(String s, String delim, boolean returnDelims); – delimiters are counted as tokens
• public StringTokenizer(String s, String delim); – delimiters are not counted as tokens
• public StringTokenizer(String s); – default delimiters (“ \t\n\r”) are not counted as tokens
CSCI 1302 – Strings 34
Using StringTokenizers
• countTokens() – Return the number of tokens in string
• hasMoreTokens() – Tells whether the string has more tokens or not
• nextToken() – return next token
CSCI 1302 – Strings 35
The Scanner class
• Can use words as the delimiter• Should be used when words, not single
characters or several single characters are delimiters
• Can parse primitive types• See TestScanner.java
CSCI 1302 – Strings 36
Command Line Arguments
• Pass arguments on the command line to main methods
• Separated by spaces, strings with spaces must be enclosed in double quotes
• Stored in the args array• See Calculator.java