Introduction To Java - MFC 158 G

Week 10 Lecture notes - Fall 2000

 

Chapter 10 -  Strings and Characters - MFC 158 (1 of 3)

 

Character constant - an integer value represented as a character in single quotes (‘a’, ‘B’, ‘\n’)

(see appendix D for integer equivalents for these characters)

 

Strings

-          a series of characters treated as a single unit (number, letters, special characters

-          in Java, a string is an OBJECT of class String.

-          String literals (or constants) are called ‘anonymous strings’  - surrounded by double quotes

-          Anonymous strings with the same contents are treated as one anonymous string object with several references, conserving memory.

 

String color = “blue”; (initializes string reference ‘color’ to refer to anonymous string object “blue”)

 

String Buffer – while strings are constants, a stringbuffer is a dynamically resizable and modifiable string.

 

Class String has nine constructors for initializing String objects in a variety of ways:

char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ','d', 'a', 'y' };

 

String s, s1, s2, s3, s4, s5, s6, s7, output;

StringBuffer buffer;

 

      s = new String( "hello" );

      buffer =

         new StringBuffer( "Welcome to Java Programming!" );

 

      // use the String constructors

      s1 = new String();

      s2 = new String( s );

      s3 = new String( charArray );

      s4 = new String( charArray, 6, 3 );  start copying at 6th offset for 3 characters

      s7 = new String( buffer ); // constructor that accepts a StringBuffer argument – this will        

                                                 // contain a copy of stringbuffer’s contents (into a string)

 

String Methods length, charAt and getChars - get information about strings

s1 = new String( "hello there" );

output += "\nLength of s1: " + s1.length();

 

// loop through the characters in s1 and display reversed

      output += "\nThe string reversed is: ";

 

      for ( int i = s1.length() - 1; i >= 0; i-- )

         output += s1.charAt( i ) + " ";

 

char charArray[];

charArray = new char[ 5 ];

s1.getChars( 0, 5, charArray, 0 ); //  copy five characters of s1, starting from position 0 into charArray

 

 

Comparing Strings - several methods available

s1 = new String( "hello" );  // create a COPY of the anonymous string "hello"

 

if ( s1.equals( "hello" ) )  // compares the contents of s1 with the anonymous string "hello"

         output += "s1 equals \"hello\"\n";

 

if ( s3.equalsIgnoreCase( s4 ) )

         output += "s3 equals s4\n";

 

// regionMatches(start index of s3, comparison string, start index of compare string,

// number of characters to compare)

if ( s3.regionMatches( 0, s4, 0, 5 ) )

         output += "First 5 characters of s3 and s4 match\n";

 

if ( s3.regionMatches( true, 0, s4, 0, 5 ) )  // same as above, except ignore case

 

Operator == works differently with objects than primitives.  The result is true if both references refer to the same object in memory.  The test below is false because we created a COPY of the anonymous string "hello" and put it into a different object - s1.  It would have been true if we changed   s1 = new String( "hello" );  to s1 = "hello";

 

if ( s1 == "hello" )  // compares

         output += "s1 equals \"hello\"\n";  // this evaluates to false //

 

StartsWith and EndsWith

String strings[] = { "started", "starting", "ended", "ending" };

for ( int i = 0; i < strings.length; i++ )

         if ( strings[ i ].startsWith( "st" ) )

            output += "\"" + strings[ i ] + "\" starts with \"st\"\n";

 

if ( strings[ i ].startsWith( "art", 2 ) )  // test starting from position 2

 

if ( strings[ i ].endsWith( "ed" ) ) // test the end of the string

 

(Note:  String method hashCode not covered in class)

 

Locating Characters and Substrings in Strings

String letters = "abcdefghijklmabcdefghijklm";

Output = "'c' is located at index " +

               letters.indexOf( 'c' ); // returns 2

output += "\n'$' is located at index " +

                letters.indexOf( '$' );   // NOT FOUND - returns a (-1)

output += "\n\nLast 'c' is located at index " +

                letters.lastIndexOf( 'c' );  // returns15

output += "\n\n\"def\" is located at index " +

                letters.indexOf( "def" );  // locates substring "def"

output += "\n\nLast \"def\" is located at index " +

                letters.lastIndexOf( "def" );  // looks for the last occurance of "def"

output += "\nLast 'a' is located at index " +

           letters.lastIndexOf( 'a', 25 );  // the highest index to begin searching backwards from

output += "\n\"def\" is located at index " +

                letters.indexOf( "def", 7 );  // the starting index to begin searching from

 

 

 

 

Extracting Substrings from strings

String letters = "abcdefghijklmabcdefghijklm";

output = "Substring from index 20 to end is " +

               "\"" + letters.substring( 20 ) + "\"\n";  //returns from index=20  'hijklm'

output += "Substring from index 0 up to 6 is " +

                "\"" + letters.substring( 0, 6 ) + "\"";   // returns 6 characters from index=0 'abcdef'

 

Concatenation of strings

String s1 = new String( "Happy " ),  s2 = new String( "Birthday" );

output += "\n\nResult of s1.concat( s2 ) = " + s1.concat( s2 );  // prints Happy Birthday-s1=Happy

 

Miscellaneous String Methods

String s1 = new String( "hello" ), s2 = new String( "GOOD BYE" ), s3 = new String( "   spaces   " );

S5 = s1.replace( 'l', 'L' );  // replace l with L in s1 - (if l exists) and returns a NEW string

S5 = s1.toUpperCase(); // converts to uppercase and returns a NEW string

S5 = s2.toLowerCase(); // converts to lowercase and returns a NEW string

S5 = s3.trim();  // removes white space at the beginning and end of the string

 

long l = 10000000;

double d = 33.333;

s1 = String.valueOf( l );  // converts long value to string

s2 = String.valueOf( d ); // converts double value to string

 

StringBuffer class - once created, a string can never change it's value.  StringBuffers allow creation and manipulation of dynamic string information - modifiable Strings.

-          if the capacity of a StringBuffer is exceeded, it is automatically expanded to include the new size.

-          Java can optimize strings better than StringBuffers, as the size of a string is always known. Use strings as much as possible for more efficient code.

StringBuffer buf1, buf2, buf3;      // 3 different constructors below //

      buf1 = new StringBuffer();   // initial capacity of 16 characters - the default //

      buf2 = new StringBuffer( 10 );  // empty, but has the capacity of 10 characters //

      buf3 = new StringBuffer( "hello" );  // contains "hello" and has capacity of 5 + 16

 

StringBuffer buf = new StringBuffer( "Hello, how are you?" );  //initial capacity is 19+16=35

buf.ensureCapacity( 75 );

output += "\n\nNew capacity = " + buf.capacity();  // buffer capacity is now 75

output += "\n Initial Length = " + buf.length();  // length is 19

buf.setLength( 10 );

output += "\n Initial Length = " + buf.length();  // length is now 10 - truncates

 

-          Other methods available with StringBuffers - charAt, setCharAt, getChars and reverse

-          StringBuffers also have append (pg 484), Insertion and Deletion operations (pg 486)

 

Class StringTokenizer - break up statements into pieces, separated by delimiters (tabs, space)

import java.util.*;

 

class stringtok {

 

public static void main(String Args []) {

 

  String stringToTokenize = "this is a sentence to break up";

  StringTokenizer tokens = new StringTokenizer( stringToTokenize );

  System.out.println( "Number of elements: " + tokens.countTokens() );

  System.out.println("The tokens are:\n");

  while ( tokens.hasMoreTokens() )         

      System.out.println( tokens.nextToken() );

 

}

 

}