chapter 9 – strings and characters 2

24
1 • Class String Recall that the content of a String object CANNOT be changed! String s = "Hello"; s += "World"; Chapter 9 – Strings and Characters 2 String Class S "Hello" "HelloWorld" S "Hello" Χ Χ The content change operation is slow.

Upload: shayla

Post on 13-Jan-2016

63 views

Category:

Documents


2 download

DESCRIPTION

Χ. Χ. "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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 9 – Strings and Characters 2

1

• Class String– Recall that the content of a String object CANNOT be

changed!

String s = "Hello";

s += "World";

Chapter 9 – Strings and Characters 2

String Class

S "Hello"

"HelloWorld"

S "Hello"Χ Χ

– The content change operation is slow.

Page 2: Chapter 9 – Strings and Characters 2

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

Page 3: Chapter 9 – Strings and Characters 2

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.

Page 4: Chapter 9 – Strings and Characters 2

4

Examplepublic 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 StringBufferConstructorsbuffer1 = "" has capacity 16buffer2 = "" has capacity 10buffer3 = "hello" has capacity 21

Page 5: Chapter 9 – Strings and Characters 2

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.

Page 6: Chapter 9 – Strings and Characters 2

6

Exampleclass 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 StringBufferCapLenbuf = "Hello World"length = 11capacity = 27New capacity = 56New buf = "Hello"New length = 5New capacity = 56

Page 7: Chapter 9 – Strings and Characters 2

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

Page 8: Chapter 9 – Strings and Characters 2

8

Exampleclass 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 StringBufferCharsbuf = hello thereCharacter at 0: hCharacter at 4: o

New buf = Hello There

Reserved buf = erehT olleH

Page 9: Chapter 9 – Strings and Characters 2

9

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

Page 10: Chapter 9 – Strings and Characters 2

10

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

Page 11: Chapter 9 – Strings and Characters 2

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

Page 12: Chapter 9 – Strings and Characters 2

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

Page 13: Chapter 9 – Strings and Characters 2

13

Examplepublic 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 StringBufferInsertbuffer after inserts: Hello, Big Worldbuffer after deleteCharAt(10): Hello, BigWorldbuffer after delete(2, 6): He BigWorld

Page 14: Chapter 9 – Strings and Characters 2

14

Character Class Examples

• Treat primitive variables as objects– Type wrapper classes

• Boolean• Character• Double• Float• Byte• Short• Integer• Long

– We examine class Character

Page 15: Chapter 9 – Strings and Characters 2

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.

Page 16: Chapter 9 – Strings and Characters 2

16

Example• Test the effect of methods of Character.

Page 17: Chapter 9 – Strings and Characters 2

17

import java.awt.*;import java.awt.event.*;

// Java extension packagesimport 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 );

Page 18: Chapter 9 – Strings and Characters 2

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

Page 19: Chapter 9 – Strings and Characters 2

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

Page 20: Chapter 9 – Strings and Characters 2

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.

Page 21: Chapter 9 – Strings and Characters 2

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.

Page 22: Chapter 9 – Strings and Characters 2

22

Example 1import 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 TestStringTokenizer1JavaProgrammingisveryinteresting!Ilikeit.

Page 23: Chapter 9 – Strings and Characters 2

23

Example 2import 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

1225632799

delimiter characters

• What is the output if no delimiter is set?

StringTokenizer st = new StringTokenizer( "12, 25, 63, 27, 99");

Page 24: Chapter 9 – Strings and Characters 2

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