1 / 24

Chapter 9 – Strings and Characters 2

Χ. Χ. "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.

shayla
Download Presentation

Chapter 9 – Strings and Characters 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Χ Χ "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.

  2. 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, ....)

  3. 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.

  4. 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

  5. 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.

  6. 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

  7. 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

  8. 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

  9. 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.

  10. 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( ' ' );

  11. 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

  12. 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

  13. 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

  14. Character Class Examples • Treat primitive variables as objects • Type wrapper classes • Boolean • Character • Double • Float • Byte • Short • Integer • Long • We examine class Character

  15. 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.

  16. Example • Test the effect of methods of Character.

  17. 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 );

  18. 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

  19. 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".

  20. 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.

  21. 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.

  22. 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.

  23. 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");

  24. 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

More Related