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()
          Returns the length of this string.

 char

charAt(int index)
          Returns the character at the specified index.

 void

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
          Copies characters from this string into the destination character array.

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)
          Compares this string to the specified object.

 boolean

equalsIgnoreCase(String anotherString)
          Compares this String to another String, ignoring case considerations.

int

compareTo(String anotherString)
          Compares two strings lexicographically

 

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)
          Tests if two string regions are equal.

 boolean

regionMatches(int toffset, String other, int ooffset, int len)
          Tests if two string regions are equal.

View and Run: StringCompare.java

More Comparisons StartsWith and EndsWith

 boolean

startsWith(String prefix)
          Tests if this string starts with the specified prefix.

 boolean

startsWith(String prefix, int toffset)
          Tests if this string starts with the specified prefix beginning a specified index.

boolean

endsWith(String suffix)
          Tests if this string ends with the specified suffix.

Locating Characters and Substrings in Strings

int

indexOf(int ch)
          Returns the index within this string of the first occurrence of the specified character.

 int

indexOf(int ch, int fromIndex)
          Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

 int

indexOf(String str)
          Returns the index within this string of the first occurrence of the specified substring.

 int

indexOf(String str, int fromIndex)
          Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

 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.

Extracting Substrings from Strings

 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.

Concatenating Strings

 String

concat(String str)
          Concatenates the specified string to the end of this string.

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()
          Converts all of the characters in this String to lower case

 String

toUpperCase()
          Converts all of the characters in this String to upper case

String

replace(char oldChar, char newChar)
          Returns a new string resulting from replacing all occurrences of oldChar in this string with 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()
          Constructs a string buffer with no characters in it and an initial capacity of 16 characters.

 

StringBuffer(int length)
          Constructs a string buffer with no characters in it and an initial capacity specified by the length argument.

 

StringBuffer(String str)
          Constructs a string buffer so that it represents the same sequence of characters as the string argument; in other words, the initial contents of the string buffer is a copy of the argument string.

 

Append Method

Append works with all data types, for example you can append an int to your StringBuffer

 StringBuffer

append(int i)
          Appends the string representation of the int argument to this string buffer.

Example:

StringBuffer s1;

s1 = new StringBuffer("Hello"

String

toString()
          Converts to a string representing the data in this string buffer.

);

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.

StringBuffer

insert(int offset, String str)
          Inserts the string into this string buffer.

void

setLength(int newLength)
          Sets the length of this String buffer.

String

toString()
          Converts to a string representing the data in this string buffer.

void

setCharAt(int index, char ch)
          The character at the specified index of this string buffer is set to 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()
          Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

 boolean

hasMoreTokens()
          Tests if there are more tokens available from this tokenizer's string.

 String

nextToken()

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:

  1. Determine if the hand contains a pair
  2. Determine if the hand contains two-pairs
  3. Determine if the hand contains three of a kind
  4. Determine if the hand contains four of a kind
  5. Determine if the hand contains a flush
  6. Determine if the hand contains a straight
  7. Determine if the hand contains a full house

Enrichment: Deal two hands and decide which one is better.