Introduction
To Java - MFC 158 G
Week
10 Lecture notes - Fall 2000
�
Chapter 10 -� Strings and Characters - MFC 158 (1 of 3)
<![if !supportEmptyParas]>�<![endif]>
Character constant - an integer value represented as a character in single quotes (�a�, �B�, �\n�)
(see appendix D for integer equivalents for these characters)
<![if !supportEmptyParas]>�<![endif]>
Strings
<![if !supportLists]>-��������� <![endif]>a series of characters treated as a single unit (number, letters, special characters
<![if !supportLists]>-��������� <![endif]>in Java, a string is an OBJECT of class String.
<![if !supportLists]>-��������� <![endif]>String literals (or constants) are called �anonymous strings�� - surrounded by double quotes
<![if !supportLists]>-��������� <![endif]>Anonymous strings with the same contents are treated as one anonymous string object with several references, conserving memory.
<![if !supportEmptyParas]>�<![endif]>
String color = �blue�; (initializes string reference �color� to refer to anonymous string object �blue�)
<![if !supportEmptyParas]>�<![endif]>
String Buffer � while strings are constants, a stringbuffer is a dynamically resizable and modifiable string.
<![if !supportEmptyParas]>�<![endif]>
Class String has nine constructors for initializing String objects in a variety of ways:
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ','d', 'a', 'y' }; <![if !supportEmptyParas]>�<![endif]> String s, s1, s2, s3, s4, s5, s6, s7, output; StringBuffer buffer; <![if !supportEmptyParas]>�<![endif]> ����� s = new String( "hello" ); ����� buffer = �������� new StringBuffer( "Welcome to Java Programming!" ); <![if !supportEmptyParas]>�<![endif]> ����� // 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) |
<![if !supportEmptyParas]>�<![endif]>
String Methods length, charAt and getChars - get information about strings
s1 = new String( "hello there" ); output += "\nLength of s1: " + s1.length(); <![if !supportEmptyParas]>�<![endif]> // loop through the characters in s1 and display reversed ����� output += "\nThe string reversed is: "; <![if !supportEmptyParas]>�<![endif]> ����� for ( int i = s1.length() - 1; i >= 0; i-- ) �������� output += s1.charAt( i ) + " "; <![if !supportEmptyParas]>�<![endif]> char charArray[]; charArray = new char[ 5 ]; s1.getChars( 0, 5, charArray, 0 ); //� copy five characters of s1, starting from position 0 into charArray |
<![if !supportEmptyParas]>�<![endif]>
<![if !supportEmptyParas]>�<![endif]>
Comparing Strings - several methods available
s1 = new String( "hello" );� // create a COPY of the anonymous string "hello" <![if !supportEmptyParas]>�<![endif]> if ( s1.equals( "hello" ) )� // compares the contents of s1 with the anonymous string "hello" �������� output += "s1 equals \"hello\"\n"; <![if !supportEmptyParas]>�<![endif]> if ( s3.equalsIgnoreCase( s4 ) ) �������� output += "s3 equals s4\n"; <![if !supportEmptyParas]>�<![endif]> // 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 !supportEmptyParas]>�<![endif]> if ( s3.regionMatches( true, 0, s4, 0, 5 ) )� // same as above, except ignore case |
<![if !supportEmptyParas]>�<![endif]>
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 !supportEmptyParas]>�<![endif]>
if ( s1 == "hello" )� // compares
�������� output += "s1 equals \"hello\"\n";� // this evaluates to false //
<![if !supportEmptyParas]>�<![endif]>
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 !supportEmptyParas]>�<![endif]> if ( strings[ i ].startsWith( "art", 2 ) )� // test starting from position 2 <![if !supportEmptyParas]>�<![endif]> if ( strings[ i ].endsWith( "ed" ) ) // test the end of the string |
<![if !supportEmptyParas]>�<![endif]>
(Note:� String method hashCode not covered in class)
<![if !supportEmptyParas]>�<![endif]>
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 |
<![if !supportEmptyParas]>�<![endif]>
<![if !supportEmptyParas]>�<![endif]>
<![if !supportEmptyParas]>�<![endif]>
<![if !supportEmptyParas]>�<![endif]>
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' |
<![if !supportEmptyParas]>�<![endif]>
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 |
<![if !supportEmptyParas]>�<![endif]>
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 <![if !supportEmptyParas]>�<![endif]> 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 |
<![if !supportEmptyParas]>�<![endif]>
StringBuffer class - once created, a string can never change it's value.� StringBuffers allow creation and manipulation of dynamic string information - modifiable Strings.
<![if !supportLists]>-��������� <![endif]>if the capacity of a StringBuffer is exceeded, it is automatically expanded to include the new size.
<![if !supportLists]>-��������� <![endif]>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 |
<![if !supportEmptyParas]>�<![endif]>
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 |
<![if !supportEmptyParas]>�<![endif]>
<![if !supportLists]>-��������� <![endif]>Other methods available with StringBuffers - charAt, setCharAt, getChars and reverse
<![if !supportLists]>-��������� <![endif]>StringBuffers also have append (pg 484), Insertion and Deletion operations (pg 486)
<![if !supportEmptyParas]>�<![endif]>
Class StringTokenizer - break up statements into pieces, separated by delimiters (tabs, space)
import java.util.*; <![if !supportEmptyParas]>�<![endif]> class stringtok { <![if !supportEmptyParas]>�<![endif]> public static void main(String Args []) { <![if !supportEmptyParas]>�<![endif]> � 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() ); <![if !supportEmptyParas]>�<![endif]> } <![if !supportEmptyParas]>�<![endif]> } |
<![if !supportEmptyParas]>�<![endif]>
<![if !supportEmptyParas]>�<![endif]>