Class and Object

Download Report

Transcript Class and Object

StringBuffer class





Alternative to String class
Can be used wherever a string is used
More flexible than String
Has three constructors and more than 30
methods for managing the buffer and
modifying strings in the buffer
See page 266
Constructing a string buffer

Three constructors






Public StringBuffer()
StringBuffer st = new StringBuffer();
Public StringBuffer(int length)
StringBuffer st2 = new StringBuffer(10);
Public StringBuffer(String str)
StringBuffer st3 = new
StringBuffer(“Hello”);
Modifying string in the buffer

Append at the end of a string

Insert new contents at a specified
position in a string buffer

Replace characters in a string buffer
The StringTokenizer class



java.util.StringTokenizer
Used to break a string into pieces so that
information contained in it cab be retrieved
and processed.
For example, a string “I am learning Java
now”, you create an instance of a
stringTokenizer class for the string and then
retrieve individual words in the string by
using methods in StringTokenizer
Constructors for
StringTokenizer






public StringTokenizer(String s, String
delim, boolean returnTokens)
Constructs a StringTokenizer for string s with specified
delimiters. If returnTokens is true, the delimiters is
returned as a token.
Public StringTokenizer(String s, String
delim)
Constructs a Stringtokenizer for a string s with specified
delimiters delim and the delimiter is not a token
Public StringTokenizer(String s)
Constructs a StringTokenizer for string s withh default
delimiters, a space, tab, new line, and the delimiter is
not a token
Methods in StringTokenizer




int countTokens()
 Return number of tokens remaining in the
StringTokenizer
boolean hasMoreTokens()
 Return true if more token left, flase if no token
left
String nextToken()
 Return the next token(string) stored in
StringTokenizer
String nextToken(String delim)
 Return the next token(string) after reseting the
delimiter to delim
In-class practice



How do you create a string buffer from
a string? How do you get the string
from a string buffer?
Declare a StringTokenizer for a string a
with slash(/) as delimiter
Write statements to reverse a string s
using the revere method in the
StringBuffer class
In-class practice









What is the output of the following program
import java.util.StringTokenizer;
Class TestStringTokenizer{
public static void main(String[] arg){
String s= “I/am\learning Java.”;
StringTokenizer st = new StringTokenizer(s,
“/\.”);
While(st.hasMoreTokens())
System.out.print(st.nextToken() + “ “);
}}
Challenge


Write a method that checks whether
two strings are anagrams. Two strings
are anagrams if they contain the same
characters in any order. For example,
“silent” and “listen” are anagrams.
Public static boolean
isAnagrams(String s1, String s2)