A string is an object of the class String.
String colour = "blue"; //initializes String reference to colour to refer to the literal String
// (or string constant or anonymous String) object "blue"
Class String provides nine constructors for initializing String objects.
Exercise 1 - Look at seven constructors in StringConstructors.java. What are the seven strings. Look at the class documentation from Sun.
http://java.sun.com/j2se/1.4/docs/api/java/lang/String.html
Note: In most cases, it is not necessary to make a copy of an existing String object. String objects are immutable - their character contents cannot be changed after they are created.
Class StringBuffer is a dynamically resizable and modifiable string.
Some Methods
|
int |
length() |
|
|
char |
charAt(int index) |
|
|
void |
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) |
|
Common Error: "s1.length" is a syntax error, use "s1.length()"
Exercise 2: Try accessing a character at a position longer than the String. What exception is thrown?
Comparing Strings
|
boolean |
equals(Object anObject) |
|
boolean |
equalsIgnoreCase(String anotherString) |
|
int |
compareTo(String anotherString) |
Note that the == operators compares the address of two strings and not there contents! So use one of the above methods.
|
boolean |
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) |
|
boolean |
regionMatches(int toffset, String other, int ooffset, int len) |
View and Run: StringCompare.java
More Comparisons StartsWith and EndsWith
|
boolean |
startsWith(String prefix) |
|
boolean |
startsWith(String prefix, int toffset) |
|
boolean |
endsWith(String suffix) |
Locating Characters and Substrings in Strings
|
int |
indexOf(int ch) |
|
|
int |
indexOf(int ch, int fromIndex) |
|
|
int |
indexOf(String str) |
|
|
int |
indexOf(String str, int fromIndex) |
|
|
int |
lastIndexOf(int ch) |
|
|
int |
lastIndexOf(int ch, int fromIndex) |
|
Extracting Substrings from Strings
|
String |
substring(int beginIndex) |
|
String |
substring(int beginIndex, int endIndex) |
Concatenating Strings
|
String |
concat(String str) |
Note concat will not change the strings, it returns a new string
String s1 = "sea";
String s2 = "shore";
String s3 = s1.concat(s2);
c.println(s3); // outputs "seashore"
The "+" operator will also concatenated strings
String firstName = "Ada";
String lastName = "Byron";
String fullName = lastName + ", " + firstNane;
c.println(fullName); // outputs "Byron, Ada"
Converting other data types to strings.
The valueof method will convert any data type to a string.
String output;
int count = 5;
output = "The number is " + String.valueof(count);
Replacing characters in a string.
|
String |
toLowerCase() |
|
String |
toUpperCase() |
|
replace(char oldChar, char newChar) |
String s1 = "Mississippi"
String s2 = s1.replace('i', 'e');
c.println(c2); /output "Messesseppe"
StringBuffer Class
The String class provides many capabilities for processing Strings. However, once a String object is created, its contents can never be changed.
StringBuffers are used to create and manipulated dynamic string information.
Note: Performance improves if you use Strings if the contents don't need to be changed.
|
Constructor Summary |
|
|
StringBuffer() |
|
|
StringBuffer(int length) |
|
|
StringBuffer(String str) |
|
Append Method
Append works with all data types, for example you can append an int to your StringBuffer
|
StringBuffer |
append(int i) |
Example:
StringBuffer s1;
s1 = new StringBuffer("Hello"
|
toString() |
);
s1.append("there");
c.println(s1); // prints "Hello There"
Palindrome1.java in Chapter 8 of the Hoyt Examples.
/ The "Palindrome1" class.
// Determines whether or not a word is a palindrome
// by reversing the letters.
import java.awt.*;
import hsa.Console;
public class Palindrome1
{
static Console c; // The output console
public static void main (String [] args)
{
c = new Console ();
String word;
c.println ("Enter a word");
word = c.readLine ();
StringBuffer reverse = new StringBuffer ();
for (int count = word.length () - 1 ; count >= 0 ; count--)
{
reverse.append (word.charAt (count));
}
// we use cascaded method call to convert to lowercase.
if (word.toLowerCase().equals (reverse.toString ().toLowerCase()))
c.println ("The word " + word + " is a palindrome");
else
c.println ("The word " + word + " is not a palindrome");
} // main method
} // Palindrome1 class
Other useful methods:
You can use the insert method to insert any data type into a StringBuffer at the specified position.
|
insert(int offset, String str) |
|
void |
setLength(int newLength) |
|
toString() |
|
void |
setCharAt(int index, char ch) |
Example:
StringBuffer s = new StringBuffer("How it is");
s.insert(3, 7 > 6);
c.println(s.toString()); // "How true it is"
StringTokenizer Class
This class is useful for breaking a line of text into tokens, that is a sequence of characters surrounded by white space, where the consists of blanks, tabs or Returns.
The following is one example of the use of the tokenizer. The code:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
println(st.nextToken());
}
prints the following output:
this
is
a
test
The StringTokenizer methods include:
|
int |
countTokens() |
|
boolean |
hasMoreTokens() |
|
String |
Exercise:
Write a program to read a line of text and change the spelling of words ending in "or" to end in "our".
Assignment:
Modify the DeckOfCards.java so that the card-dealing method deals a five-card poker hand. Then write the following additional methods:
Enrichment: Deal two hands and decide which one is better.