Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.

Similar presentations


Presentation on theme: "1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called."— Presentation transcript:

1 1 Java Strings Dr. Randy M. Kaplan

2 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called strings In C, all of the functions to manipulate strings had to be implemented Implementing string manipulations routines is so common that programmers typically created their own libraries of these

3 3 Strings – 2 Java has two classes that make it unnecessary to implement the string data type  String  StringBuffer

4 4 Strings – 2a Anonymous Strings  When a string object appears as a string constant, for example s1.equals(“hello”)  “hello” is referred to as an anonymous string constant  Anonymous string constants having the same value are only created once to conserve memory

5 5 Strings – 3 String Constructors Strings can be constructed in several different ways s1 = new String(); s2 = new String( s ); s3 = new String( charArray ); s4 = new String( charArray, 6, 3 ); s5 = new String( byteArray, 4, 4 ); s6 = new String( byteArray ); s7 = new String( buffer );

6 6 Strings – 4 String()  An empty string (a string with 0 length) is created with the constructor without any arguments  When a string is created with this constructor, is can be used in the concatenation operation

7 7 Strings – 5 String(s)  A new string can be created from an existing string  In this case, a new string object is created and the contents of the argument is copied to the new object

8 8 Strings – 6 String(charArray)  A character array can be used to create a string  A character array is an arrays whose elements are individual characters  A string object is created by creating a string whose length is the same as the number of elements in the character array  The value of the string will be the characters contained in the array, concatenated

9 9 Strings – 7 String(charArray, 6, 3)  A new string can be created by selected particular characters from the character array  The second argument specifies the offset into the array of the first character of the string  The third argument specifies the number of characters in the character array that will make up the string  In this example, the first character of the string will be at offset 6 in the array, and three characters of the array will make up the string

10 10 Strings – 8 String(byteArray) String(byteArray, 4, 4)  Just as strings can be formed from character arrays, they can also be formed from byte arrays  The constructor that takes just a byte arrays reference copies the contents of the byte array to make the string  The constructor that takes an offset and the number of characters, works in the same way as the version which uses a character array

11 11 Strings – 9 String(buffer)  A string can also be constructed from a string buffer  The contents of the string buffer are copied to the new string object

12 12 Strings – 10 Accessing string contents  String Methods length charAt getChars

13 13 Strings – 11 public static void main( String args[] ) { String s1, output; char charArray[]; s1 = new String( "hello there" ); charArray = new char[ 5 ]; // output the string output = "s1: " + s1; // test length method output += "\nLength of s1: " + s1.length(); // loop through characters in s1 and display reversed output += "\nThe string reversed is: "; for ( int count = s1.length() - 1; count >= 0; count-- ) output += s1.charAt( count ) + " "; // copy characters from string into char array s1.getChars( 0, 5, charArray, 0 ); output += "\nThe character array is: "; for ( int count = 0; count < charArray.length; count++ ) output += charArray[ count ]; JOptionPane.showMessageDialog( null, output, "Demonstrating String Class Constructors", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

14 14 Strings – 12 The method that returns the length of the string is named length s1.length returns the length of string s1 output += "\nLength of s1: " + s1.length();

15 15 Strings – 13 To extract a character at a particular location in a string use the charAt method charAt takes an integer argument to select the character at the specified position In the example above, the character at offset count is extracted and returned output += s1.charAt( count ) + " ";

16 16 Strings – 14 A series of characters can be extracted from a string and placed in a character array The method getChars is used to accomplish this getChars takes four arguments  An initial offset into the string  A final offset one past the last character to be copied  The target character array (where the extracted characters will be stored)  The offset into the character array where the characters will be inseted s1.getChars( 0, 5, charArray, 0 );

17 17 Strings – 15 String Comparison  Java offers a variety of ways to compare String objects  Strings may be less than or greater than one another  This is determined by the lexicographic ordering of the strings  The lexicographic ordering is determined by the order of letters in the alphabet

18 18 Strings – 16 public class StringCompare { // test String class comparison methods public static void main( String args[] ) { String s1, s2, s3, s4, output; s1 = new String( "hello" ); s2 = new String( "good bye" ); s3 = new String( "Happy Birthday" ); s4 = new String( "happy birthday" ); output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n"; if ( s1.equals( "hello" ) ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n"; if ( s1 == "hello" ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n"; if ( s3.equalsIgnoreCase( s4 ) ) output += "s3 equals s4\n"; output += "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) + "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) + "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) + "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + "\n\n";

19 19 Strings – 17 if ( s3.regionMatches( 0, s4, 0, 5 ) ) output += "First 5 characters of s3 and s4 match\n"; else output += "First 5 characters of s3 and s4 do not match\n"; if ( s3.regionMatches( true, 0, s4, 0, 5 ) ) output += "First 5 characters of s3 and s4 match"; else output += "First 5 characters of s3 and s4 do not match"; JOptionPane.showMessageDialog( null, output, "Demonstrating String Class Constructors", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

20 20 Strings – 18 The equals method tests a string to determine if the string object’s value is equal to the argument of the method The method returns true if the objects are equal and false otherwise if ( s1.equals( "hello" ) ) output += "s1 equals \"hello\"\n";

21 21 Strings – 19 The == operator can also be used to test for string equality ==  For primitive data types is true when the values are the same  For references, the result is true if the references refer to the same object in memory if ( s1 == "hello" ) output += "s1 equals \"hello\"\n";

22 22 Strings – 20 If two strings are to be compared without concern for case, the method equalsIgnoreCase can be used For example, the strings “hello” and “HELLO” would be equal using equalsIgnoreCase if ( s3.equalsIgnoreCase( s4 ) ) output += "s3 equals s4\n";

23 23 Strings – 21 compareTo  The compareTo method is used to determine if one string is less than, equal to, and greater than  If the strings are equal, compareTo returns 0  If one string is less than the other, then compareTo returns a negative number  If one string is greater than the other then compareTo returns a positive number "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) +

24 24 Strings – 22 regionMatches  Compares portions of two strings for equality  First argument: starting index in the String that invokes the method  Second argument: a comparison string  Third argument: starting index in the comparison string  Fourth argument: number of characters to compare if ( s3.regionMatches( 0, s4, 0, 5 ) ) output += "First 5 characters of s3 and s4 match\n";

25 25 Strings – 23 regionMatches – Version 2  If the first argument is true, then the method ignores the case of the characters being compared  The remaining arguments are identical to those described in the first version of the method if ( s3.regionMatches( true, 0, s4, 0, 5 ) ) output += "First 5 characters of s3 and s4 match";

26 26 Strings – 24 public class StringStartEnd { public static void main( String args[] ) { String strings[] = { "started", "starting", "ended", "ending" }; String output = ""; for ( int count = 0; count < strings.length; count++ ) if ( strings[ count ].startsWith( "st" ) ) output += "\"" + strings[ count ] + "\" starts with \"st\"\n"; output += "\n"; for ( int count = 0; count < strings.length; count++ ) if ( strings[ count ].startsWith( "art", 2 ) ) output += "\"" + strings[ count ] + "\" starts with \"art\" at position 2\n"; output += "\n"; for ( int count = 0; count < strings.length; count++ ) if ( strings[ count ].endsWith( "ed" ) ) output += "\"" + strings[ count ] + "\" ends with \"ed\"\n"; JOptionPane.showMessageDialog( null, output, "Demonstrating String Class Comparisons", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

27 27 Strings – 25 startsWith  Will return true when if the string that invokes the method begins the specified character if ( strings[ count ].startsWith( "st" ) ) output += "\"" + strings[ count ] + "\" starts with \"st\"\n";

28 28 Strings – 26 endsWith  Returns true if the string that invokes the method ends with the specified string argument if ( strings[ count ].endsWith( "ed" ) ) output += "\"" + strings[ count ] + "\" ends with \"ed\"\n";

29 29 Strings – 27 hashCode Method  It is useful to be able to store Strings and other data types in a manner that allows information to be found quickly  One of the best ways to store information for fast lookup is in a hash table  A hash table stores information using a special calculation called a hash code  The hash code is used to choose the location in the table in which the object is stored

30 30 Strings – 28 Every object has the ability to be stored in a hash table Class Object defines method hashCode to perform the hashCode calculation Method hashCode is overridden by String to provide a good hash code distribution based on the contents of the String

31 31 Strings – 29 public class StringHashCode { public static void main( String args[] ) { String s1 = "hello", s2 = "Hello"; String output = "The hash code for \"" + s1 + "\" is " + s1.hashCode() + "\nThe hash code for \"" + s2 + "\" is " + s2.hashCode(); JOptionPane.showMessageDialog( null, output, "Demonstrating String Method hashCode", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

32 32 Strings – 30 The output of the hash code function

33 33 Strings – 31 Things to do with strings  Locating things within strings One of the most useful operations One of the operations that you will do most frequently Types of things to locate  Characters within strings  Strings within strings

34 34 Strings – 32 public class StringIndexMethods { // String searching methods public static void main( String args[] ) { String letters = "abcdefghijklmabcdefghijklm"; // test indexOf to locate a character in a string String output = "'c' is located at index " + letters.indexOf( 'c' ); output += "\n'a' is located at index " + letters.indexOf( 'a', 1 ); output += "\n'$' is located at index " + letters.indexOf( '$' ); // test lastIndexOf to find a character in a string output += "\n\nLast 'c' is located at index " + letters.lastIndexOf( 'c' );

35 35 Strings – 33 output += "\nLast 'a' is located at index " + letters.lastIndexOf( 'a', 25 ); output += "\nLast '$' is located at index " + letters.lastIndexOf( '$' ); // test indexOf to locate a substring in a string output += "\n\n\"def\" is located at index " + letters.indexOf( "def" ); output += "\n\"def\" is located at index " + letters.indexOf( "def", 7 ); output += "\n\"hello\" is located at index " + letters.indexOf( "hello" );

36 36 Strings – 34 // test lastIndexOf to find a substring in a string output += "\n\nLast \"def\" is located at index " + letters.lastIndexOf( "def" ); output += "\nLast \"def\" is located at index " + letters.lastIndexOf( "def", 25 ); output += "\nLast \"hello\" is located at index " + letters.lastIndexOf( "hello" ); JOptionPane.showMessageDialog( null, output, "Demonstrating String Class \"index\" Methods", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

37 37 Strings – 35 The fundamental string searching method is indexOf indexOf can take various arguments including  Characters  Strings  Starting location for the search

38 38 Strings – 36 indexOf Examples Assume the following String letters = "abcdefghijklmabcdefghijklm";

39 39 Strings – 37 Search for a character String output = "'c' is located at index " + letters.indexOf( 'c' );  When a character argument is passed, the position of the first occurrence of the character is returned  In this example, the output will be 2

40 40 Strings – 38 You can specify the starting location of a search for a particular character as in the following output += "\n'a' is located at index " + letters.indexOf( 'a', 1 );  This begins its search at position 1 in the string

41 41 Strings – 39 When the character is not found, indexOf will return a -1 output += "\nLast '$' is located at index " + letters.lastIndexOf( '$' );

42 42 Strings – 40 It is also possible to locate a substring within a string output += "\n\nLast \"def\" is located at index " + letters.indexOf( "def" ); And likewise, it is possible to specify the starting position for a search when searching for a string output += "\n\"def\" is located at index " + letters.indexOf( "def", 7 );

43 43 Strings – 41 A variation of indexOf is the method lastIndexOf Siminar to indexOf, last index of will return the index of a character or a string occurrence within a string Instead of returning the index of the first occurrence, lastIndexOf returns the index of the last occurrence

44 44 Strings – 42 Search for the last occurrence of the character ‘c’ and return its index output += "\n\nLast 'c' is located at index " + letters.lastIndexOf( 'c' ); Search for the last occurrence of the character ‘a’ beginning at position 25 in the string output += "\nLast 'a' is located at index " + letters.lastIndexOf( 'a', 25 );

45 45 Strings – 43 Search for the last occurrence of the string “def” in the string output += "\n\nLast \"def\" is located at index " + letters.lastIndexOf( "def" ); Search for the last occurrence of the string “def” beginning at position 25 in the string output += "\nLast \"def\" is located at index " + letters.lastIndexOf( "def", 25 );

46 46 Strings – 44 Extracting Substrings from Strings  Another extremely useful operation  The method provided for this is named “subString”  Two variations of subString One argument (where to start) Two arguments  Where to start  Where to end

47 47 Strings – 45 public class SubString { // test String substring methods public static void main( String args[] ) { String letters = "abcdefghijklmabcdefghijklm"; // test substring methods String output = "Substring from index 20 to end is " + "\"" + letters.substring( 20 ) + "\"\n"; output += "Substring from index 0 up to 6 is " + "\"" + letters.substring( 0, 6 ) + "\""; JOptionPane.showMessageDialog( null, output, "Demonstrating String Class Substring Methods", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

48 48 Strings – 46 Extract the string beginning at position 20 through the end of the original string String output = "Substring from index 20 to end is " +"\"" + letters.substring( 20 ) + "\"\n";

49 49 Strings – 47 Extract the string beginning at position 0 through position 6 output += "Substring from index 0 up to 6 is " + "\"" + letters.substring( 0, 6 ) + "\"";

50 50 Strings – 48 Concatenation  We have used string concatenation in the form of an operator in an expression  When the + operator is used for strings, the operation it performs is to concatenate its operands  String output = "s1 = " + s1 + "\ns2 = " + s2;

51 51 Strings – 49 Alternatively there is also a method that is defined for concatenation The method concat takes an argument as a string and returns an object that is the concatenation of the string invoking the method and the string argument s1.concat(s2) is equivalent to s1 + s2

52 52 Strings – 50 Other Methods  replace  toUpperCase  toLowerCase  trim  toCharArray

53 53 Strings – 51 s1.replace( 'l', 'L' ); Replace all occurrences of l with L in the string s1

54 54 Strings – 52 "\n\ns1.toUpperCase() = " + s1.toUpperCase() + Return a new string object where all lower case characters have been transformed to uppercase "\ns2.toLowerCase() = " + s2.toLowerCase(); Return a string where all upper case characters have been transformed to lower case

55 55 Strings – 53 output += "\n\ns3 after trim = \"" + s3.trim() + "\""; Trim all white space characters in s3 that occur at the beginning or at the end of s3 A new string object is returned

56 56 Strings – 54 An object can be transformed into a String object with the toString method (if one has been defined for it) An object can be transformed into a character array with the toCharArray method

57 57 Strings – 55 Another typical “programming” operation is the conversion from one type to a string type In C this was accomplished with a special function: sprint A special class method exists for this purpose called valueOf

58 58 Strings – 56 valueOf can take many different types of arguments  charArray  boolean  char  int  long  float  double

59 59 Strings – 57 The purpose of the valueOf methods is to return a string representation of its argument So, for example, if an integer is passed to the method, the string representation of that integer is returned

60 60 Strings – 58 public static void main( String args[] ) { char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean b = true; char c = 'Z'; int i = 7; long l = 10000000; float f = 2.5f; double d = 33.333; Object o = "hello"; // assign to an Object reference String output; output = "char array = " + String.valueOf( charArray ) + "\npart of char array = " + String.valueOf( charArray, 3, 3 ) + "\nboolean = " + String.valueOf( b ) + "\nchar = " + String.valueOf( c ) + "\nint = " + String.valueOf( i ) + "\nlong = " + String.valueOf( l ) + "\nfloat = " + String.valueOf( f ) + "\ndouble = " + String.valueOf( d ) + "\nObject = " + String.valueOf( o );

61 61 Strings – 59 intern  Comparing a large String object is a relatively slow operation  When the String method intern is invoked on a String object A reference is returned The object is guaranteed to have the same contents as the original string

62 62 Strings – 60 intern again  More importantly – If intern is invoked again on a String object that it previously had been invoked on It will return a reference to the same object it created previously This object is maintained in memory by the Class String Large strings can be compared quickly using intern through the use of the == operator

63 63 Strings – 61 The StringBuffer Class  Very similar to String  Except Once a String is created, its contents cannot be changed  StringBuffer is used to create and manage dynamic strings strings that will change over time

64 64 Strings – 62 StringBuffer Constructors  Create a StringBuffer with no characters but an initial capacity of 16 characters  Create a StringBuffer with no characters of a specified capacity  Create a StringBuffer using a source String object as its argument

65 65 Strings – 63 public static void main( String args[] ) { StringBuffer buffer1, buffer2, buffer3; buffer1 = new StringBuffer(); buffer2 = new StringBuffer( 10 ); buffer3 = new StringBuffer( "hello" ); String output = "buffer1 = \"" + buffer1.toString() + "\"" + "\nbuffer2 = \"" + buffer2.toString() + "\"" + "\nbuffer3 = \"" + buffer3.toString() + "\"";

66 66 Strings – 64 It is important to note that StringBuffers are NOT STRING objects They cannot be used interchangeably with String objects They need to be converted to strings before they can be used as strings  The method toString applies


Download ppt "1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called."

Similar presentations


Ads by Google