240 likes | 454 Views
Χ. Χ. "HelloWorld". "Hello". "Hello". S. S. Chapter 9 – Strings and Characters 2. String Class. Class String Recall that the content of a String object CANNOT be changed! String s = "Hello"; s += "World";. The content change operation is slow. StringBuffer Class.
E N D
Χ Χ "HelloWorld" "Hello" "Hello" S S Chapter 9 – Strings and Characters 2 String Class • Class String • Recall that the content of a String object CANNOT be changed! • String s = "Hello"; • s += "World"; • The content change operation is slow.
StringBuffer Class • Class StringBuffer • Used for creating and manipulating dynamic string data • i.e., modifiable Strings • Can store characters based on capacity • Capacity expands dynamically to handle additional characters • CANNOT use operators + and += for string concatenation • Fewer utility methods (e.g. no substring, trim, ....)
StringBuffer Constructors • Three StringBuffer constructors • public StringBuffer(); • empty content, initial capacity of 16 characters • public StringBuffer(int length); • empty content, initial capacity of length characters • public StringBuffer(String str); • contain the characters of str, capacity is the number of characters in str plus 16 • Use capacity() method to get the capacity. • If the internal buffer overflows, the capacity is automatically made larger.
Example public class StringBufferConstructors { // test StringBuffer constructors public static void main( String[] args ) { StringBuffer buffer1, buffer2, buffer3; buffer1 = new StringBuffer(); buffer2 = new StringBuffer( 10 ); buffer3 = new StringBuffer( "hello" ); System.out.print("buffer1 = \"" + buffer1.toString() + "\""); System.out.println(" has capacity " + buffer1.capacity()); System.out.print("buffer2 = \"" + buffer2.toString() + "\""); System.out.println(" has capacity " + buffer2.capacity()); System.out.print("buffer3 = \"" + buffer3.toString() + "\""); System.out.println(" has capacity " + buffer3.capacity()); } } >java StringBufferConstructors buffer1 = "" has capacity 16 buffer2 = "" has capacity 10 buffer3 = "hello" has capacity 21
StringBuffer Methods length, capacity, setLength and ensureCapacity • Method length • Return StringBuffer length (the actual number of characters stored). • Method capacity • Return StringBuffer capacity (the number of characters can be stored without expansion) • Method setLength • Increase or decrease StringBuffer length. If the new length is less than the current length of the string buffer, the string buffer is truncated. • Method ensureCapacity • Set StringBuffer capacity • The new capacity is the larger of the minimumCapacity argument or twice the old capacity plus 2.
Example class StringBufferCapLen { public static void main(String[] args) { StringBuffer buf; buf = new StringBuffer( "Hello World" ); System.out.println( "buf = \"" + buf +"\""); System.out.println( "length = " + buf.length() ); System.out.println( "capacity = " + buf.capacity()); buf.ensureCapacity( 50 ); System.out.println( "New capacity = " + buf.capacity()); buf.setLength( 5 ); System.out.println( "New buf = \"" + buf +"\""); System.out.println( "New length = " + buf.length()); System.out.println( "New capacity = " + buf.capacity()); } } >java StringBufferCapLen buf = "Hello World" length = 11 capacity = 27 New capacity = 56 New buf = "Hello" New length = 5 New capacity = 56
StringBuffer Methods charAt, setCharAt and reverse • Manipulating StringBuffer characters • Method charAt • Return StringBuffer character at specified index • Method setCharAt • Set StringBuffer character at specified index • Method reverse • Reverse StringBuffer contents
Example class StringBufferChars { public static void main(String[] args) { StringBuffer buf; buf = new StringBuffer( "hello there" ); System.out.println( "buf = " + buf); System.out.println( "Character at 0: " + buf.charAt( 0 )); System.out.println( "Character at 4: " + buf.charAt( 4 )); buf.setCharAt( 0, 'H' ); buf.setCharAt( 6, 'T' ); System.out.println( "\nNew buf = " + buf ); buf.reverse(); System.out.println( "\nReserved buf = " + buf ); } } >java StringBufferChars buf = hello there Character at 0: h Character at 4: o New buf = Hello There Reserved buf = erehT olleH
StringBufferappend Methods • Method append • Allow data-type values to be added to StringBuffer • Should NOT use + and += for StringBuffer • Overloaded methods to append primitive data type values, String, char array and the String representation of any Objects.
Example class StringBufferAppend { public static void main(String[] args) { Object obj = "hello"; // Assign String to Object reference String s = "good bye"; char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean b = true; char c = 'Y'; int i = 7; long lg = 10000000; float f = 2.5f; double d = 33.333; StringBuffer buf; buf = new StringBuffer(); buf.append( obj ); buf.append( ' ' ); buf.append( s ); buf.append( ' ' ); buf.append( charArray ); buf.append( ' ' ); buf.append( charArray, 0, 3 ); buf.append( ' ' ); buf.append( b ); buf.append( ' ' );
Example buf.append( c ); buf.append( ' ' ); buf.append( i ); buf.append( ' ' ); buf.append( lg ); buf.append( ' ' ); buf.append( f ); buf.append( ' ' ); buf.append( d ); System.out.println( "buf = " + buf.toString() ); } } >java StringBufferAppend buf = hello good bye abcdef abc true Y 7 10000000 2.5 33.333
StringBuffer Insertion and Deletion Methods • Method insert • Similar to append and can specify where to insert • Methods delete and deleteCharAt • Allow characters to be removed from StringBuffer • delete : delete a range of characters, from start to end-1 • deleteCharAt : delete a character at a specified location
Example public class StringBufferInsert { // test StringBuffer insert methods public static void main( String[] args ) { StringBuffer buffer = new StringBuffer("Hello World"); buffer.insert( 5, ", Big"); System.out.println("buffer after inserts: " + buffer); buffer.deleteCharAt( 10 ); System.out.println("buffer after deleteCharAt(10): "+buffer); buffer.delete( 2, 6 ); System.out.println("buffer after delete(2, 6): " + buffer); } } >java StringBufferInsert buffer after inserts: Hello, Big World buffer after deleteCharAt(10): Hello, BigWorld buffer after delete(2, 6): He BigWorld
Character Class Examples • Treat primitive variables as objects • Type wrapper classes • Boolean • Character • Double • Float • Byte • Short • Integer • Long • We examine class Character
Character Class Methods • The Character class has a set of isXXXX() methods. • public static boolean isDigit(char ch); • Determines whether the specified character is a digit character (i.e. '0' - '9'). • It also provides character conversion methods. • public static char toLowerCase(char ch); • returns the lowercase equivalent of the character, if any; otherwise, the character itself. • public static char toUpperCase(char ch); • returns the uppercase equivalent of the character, if any; otherwise, the character itself.
Example • Test the effect of methods of Character.
import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; public class StaticCharMethods extends JApplet implements ActionListener { private char c; private JLabel promptLabel; private JTextField inputField; private JTextArea outputArea; // set up GUI public void init() { Container container = getContentPane(); container.setLayout( new FlowLayout() ); promptLabel = new JLabel( "Enter a character and press Enter" ); container.add( promptLabel ); inputField = new JTextField( 5 ); inputField.addActionListener(this); container.add( inputField );
outputArea = new JTextArea( 10, 20 ); container.add( outputArea ); } public void actionPerformed( ActionEvent event ){ c = inputField.getText().charAt( 0 ); buildOutput(); } // display character info in outputArea public void buildOutput() { outputArea.setText( "is defined: " + Character.isDefined( c ) + "\nis digit: " + Character.isDigit( c ) + "\nis Java letter: " + Character.isJavaIdentifierStart( c ) + "\nis Java letter or digit: " + Character.isJavaIdentifierPart( c ) + "\nis letter: " + Character.isLetter( c ) + "\nis letter or digit: " + Character.isLetterOrDigit( c ) + "\nis lower case: " + Character.isLowerCase( c ) + "\nis upper case: " + Character.isUpperCase( c ) + "\nto upper case: " + Character.toUpperCase( c ) + "\nto lower case: " + Character.toLowerCase( c ) ); } } // end class StaticCharMethods
Class StringTokenizer • Java has a utility class StringTokenizer to break up a string into individual pieces (tokens). • StringTokenizer is defined in java.util package. • Partition String into individual substrings • e.g. In the string "23 71 55 27", if the delimiter (separator) is the space character, the tokens are "23", "71", "55'" and "27".
Class StringTokenizer // Constructors public StringTokenizer(String str); Constructs a string tokenizer for the specified string. The default delimiter set is " \t\n\r", the space character, the tab character, the newline character, and the carriage return character. public StringTokenizer(String str, String delim); Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens. // Methods public int countTokens(); Return the number of tokens remaining in the string using the current delimiter set.
Class StringTokenizer public boolean hasMoreTokens(); Returns true if and only if there is at least one token in the string after the current position; false otherwise. public String nextToken(); Returns the next token from this string tokenizer. public String nextToken(String delim); Return the next token, after switching to the new delimiter set.
Example 1 import java.util.*; public class TestStringTokenizer1 { public static void main( String[] args ) { StringTokenizer st = new StringTokenizer( "Java Programming is very interesting! I like it." ); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } >java TestStringTokenizer1 Java Programming is very interesting! I like it.
Example 2 delimiter characters import java.util.*; public class TestStringTokenizer2 { public static void main( String args[] ) { StringTokenizer st = new StringTokenizer( "12, 25, 63, 27, 99", " ,"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } >java TestStringTokenizer2 12 25 63 27 99 • What is the output if no delimiter is set? • StringTokenizer st = new StringTokenizer( • "12, 25, 63, 27, 99");
Exercise • Write a program that reads in a sentence (from the user or from the command line) and prints it out with each word reversed, but with the words in the original order: C:\> java ReverseWords "Go to the main menu. Quick!" oG ot eht niam .unem !kciuQ