1 / 28

Chapter 8 – Strings and Characters 1

Chapter 8 – Strings and Characters 1. Introduction. String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer. Fundamentals of Strings. String Series of characters treated as single unit

ban
Download Presentation

Chapter 8 – Strings and Characters 1

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. Chapter 8 – Strings and Characters 1 Introduction • String and character processing • Class java.lang.String • Class java.lang.StringBuffer • Class java.lang.Character • Class java.util.StringTokenizer

  2. Fundamentals of Strings • String • Series of characters treated as single unit • May include letters, digits, etc. • Object of class String • You should refer to http://java.sun.com for the API details • Once created the content stored in a String object cannot be changed (immutable). • Java provides a rich library for manupilating Strings.

  3. String Constructors • String has the following constructors: • public String(); • public String(byte ascii[]); • public String(byte ascii[], int offset, int count); • public String(char value[]); • public String(char value[], int offset, int count); • public String(String value); • public String(StringBuffer buffer);

  4. Example // StringConstructors.java // This program demonstrates the String class constructors. public class StringConstructors { public static void main (String args[]) { char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; byte byteArray[] = { 'n', 'e', 'w', ' ', 'y', 'e', 'a', 'r' }; StringBuffer buffer; String s, s1, s2, s3, s4, s5, s6, s7; s = new String( "hello" ); buffer = new StringBuffer(); buffer.append( "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 ); s5 = new String( byteArray, 4, 4 ); s6 = new String( byteArray ); s7 = new String( buffer );

  5. System.out.println( "s1 = " + s1 ); System.out.println( "s2 = " + s2 ); System.out.println( "s3 = " + s3 ); System.out.println( "s4 = " + s4 ); System.out.println( "s5 = " + s5 ); System.out.println( "s6 = " + s6 ); System.out.println( "s7 = " + s7 ); } } Output s1 = s2 = hello s3 = birth day s4 = day s5 = year s6 = new year s7 = Welcome to Java Programming!

  6. String Methods length, charAt and getChars • Method length • Determine String length • Like arrays, Strings always “know” their size • Unlike array, Strings do not have length instance variable • Method charAt • Get character at specific location in String • Like array, the first character begins with index 0 • Method getChars • Get entire set of characters in String • void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin); • Copies characters from this string into the destination char array. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1.

  7. Example >java StringMiscellaneous s1: hello there Length of s1: 11 The string reversed is: e r e h t o l l e h The character array is: there public class StringMiscellaneous { public static void main( String args[] ){ String s1, output = ""; char charArray[] = new char[ 5 ];; s1 = new String( "hello there" ); // output the string System.out.println("s1: " + s1); // test length method System.out.println("Length of s1: " + s1.length()); // loop through characters in s1 and display reversed System.out.println("The string reversed is: "); for ( int count = s1.length() - 1; count >= 0; count-- ) System.out.print( s1.charAt(count) + " " ); // copy characters from string into char array s1.getChars( 6, 11, charArray, 0 ); System.out.println("\nThe character array is: "); for ( int count = 0; count < charArray.length; count++ ) output += charArray[ count ]; System.out.println(output); } } // end class StringMiscellaneous

  8. Comparing Strings • You CANNOT use relational operators like ==, <= to compare two Strings. • String class provides the following methods for comparing two strings public int compareTo(String anotherString); Returns the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument. public boolean equals(Object anObject);Returns true if the Strings are equal; false otherwise. public boolean equalsIgnoreCase(String anotherString);Returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.

  9. Example public class StringCompare { 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"; // test for equality if ( s1.equals( "hello" ) ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n"; // test for equality with == if ( s1 == "hello" ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n"; >java StringCompare s1 = hello s2 = good bye s3 = Happy Birthday s4 = happy birthday s1 equals "hello" s1 does not equal "hello"

  10. Example >java StringCompare s1 = hello s2 = good bye s3 = Happy Birthday s4 = happy birthday ....... s3 equals s4 s1.compareTo( s2 ) is 1 s2.compareTo( s1 ) is -1 s1.compareTo( s1 ) is 0 s3.compareTo( s4 ) is -32 s4.compareTo( s3 ) is 32 // test for equality (ignore case) if ( s3.equalsIgnoreCase( s4 ) ) output += "s3 equals s4\n"; else output += "s3 does not equal s4\n"; // test compareTo 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"; System.out.print( output ); } }

  11. StartsWith and EndsWith • boolean startsWith(String prefix) • Tests if this string starts with the specified prefix. • boolean endsWith(String suffix) • Tests if this string ends with the specified suffix.

  12. Example public class StringStartEnd { public static void main( String args[] ) { String strings[] = { "started", "starting", "ended", "ending" }; String output = ""; // test method startsWith for ( int count = 0; count < strings.length; count++ ) if ( strings[ count ].startsWith( "st" ) ) output += "\"" + strings[ count ] + "\" starts with \"st\"\n"; output += "\n"; // test method endsWith for ( int count = 0; count < strings.length; count++ ) if ( strings[ count ].endsWith( "ed" ) ) output += "\"" + strings[ count ] + "\" ends with \"ed\"\n"; System.out.print( output ); } } // end class StringStartEnd >java StringStartEnd "started" starts with "st" "starting" starts with "st" "started" ends with "ed" "ended" ends with "ed"

  13. Locating Characters and Substrings in Strings • To locate a character or a substring in a String Object, you can use the overloaded indexOf()and lastIndexOf() public int indexOf(int ch); public int indexOf(int ch, int fromIndex); the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur. public int indexOf(String str); public int indexOf(String str, int fromIndex); public int lastIndexOf(int ch); public int lastIndexOf(int ch, int fromIndex); public int lastIndexOf(String str); public int lastIndexOf(String str, int fromIndex); If the string argument occurs as a substring within this object at a starting index no greater than fromIndex then the index of the first character of the last such substring is returned. If it does not occur as a substring starting at fromIndex or earlier, -1 is returned.

  14. Example class StringIndexMethods { public static void main (String args[]) { String letters = "abcdefghijklmabcdefghijklm"; // test indexOf to locate a character in a string System.out.println("'c' is located at index " + letters.indexOf('c') ); System.out.println("'a' is located at index " + letters.indexOf('a', 1 ) ); System.out.println("'$' is located at index " + letters.indexOf('$' ) ); System.out.println(); // test lastIndexOf to find a substring in a string System.out.println("Last \"def\" is located at index " + letters.lastIndexOf( "def" ) ); System.out.println("Last \"def\" is located at index " + letters.lastIndexOf( "def", 10 ) ); System.out.println("Last \"hello\" is located at index " + letters.lastIndexOf( "hello" ) ); } }

  15. Output letters = "abcdefghijklmabcdefghijklm"; >java StringIndexMethods 'c' is located at index 2 'a' is located at index 13 '$' is located at index -1 Last "def" is located at index 16 Last "def" is located at index 3 Last "hello" is located at index -1

  16. Extracting Substrings from Strings • String class provides the following methods for extracting substrings: public String substring(int beginIndex); public String substring(int beginIndex, int endIndex); Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. • Example: if s = "hamburger", • s.substring(3) returns "burger" • s.substring(6) returns "ger" • s.substring(9) returns "" (an empty string) • s.substring(4, 8) returns "urge" • s.substring(1, 3) returns "am"

  17. Example class StringSubstring { public static void main (String args[]) { String letters = "abcdefghijklmabcdefghijklm"; // test substring System.out.println( "\nSubstring from index 20 to end is " + "\"" + letters.substring( 20 ) + "\""); System.out.println( "Substring from index 0 upto 6 is " + "\"" + letters.substring( 0, 6 ) + "\""); } } >java StringSubstring Substring from index 20 to end is "hijklm" Substring from index 0 upto 6 is "abcdef"

  18. Miscellaneous String Methods • String class has several methods that return modified copies of a string object to a character array: • public String concat(String str); • public String replace(char oldChar, char newChar); • returns a string derived from this string by replacing every occurrence of oldChar with newChar. • public char[] toCharArray(); • public String toLowerCase(); • public String toString(); • public String toUpperCase(); • public String trim(); • returns this string, with whitespace removed from the front and end

  19. Example class StringMisc { public static void main (String args[]) { String s1 = new String( "hello" ), s2 = new String( "GOOD BYE" ), s3 = new String( " spaces " ); System.out.println( ); // test method replace System.out.println( "Replace 'l' with 'L' in s1: " + s1.replace( 'l', 'L' ) ); System.out.println( ); // test toLowerCase and toUpperCase System.out.println( "s1 after toUpperCase = " + s1.toUpperCase() ); System.out.println( "s2 after toLowerCase = " + s2.toLowerCase() ); System.out.println( ); >java StringMisc Replace 'l' with 'L' in s1: heLLo s1 after toUpperCase = HELLO s2 after toLowerCase = good bye

  20. Example // test trim method System.out.println( "s3 after trim = \"" + s3.trim() + "\""); System.out.println( ); // test toString method System.out.println( "s1 = " + s1.toString() ); System.out.println( ); // test toCharArray method char charArray[] = s1.toCharArray(); System.out.println( "s1 as a character array = " ); for ( int i = 0; i < charArray.length; i++ ) { System.out.print( charArray[i]); // use method print(char) System.out.print( " " ); } System.out.println(); } } >java StringMisc ....... s3 after trim = "spaces" s1 = hello s1 as a character array = h e l l o

  21. Using String Method valueOf • Java provides a set of static valueOf methods that takes arguments of various types, convert those arguments to strings and return them as String objects. • public static String valueOf(boolean b); • public static String valueOf(char c); • public static String valueOf(char data[]); • public static String valueOf(char data[], int offset, int count); • public static String valueOf(double d); • public static String valueOf(float f); • public static String valueOf(int i);

  22. Important! • All the above String methods do NOT modify the String itself. It just return a NEW String objects. class S2 { public static void main (String args[]) { String s = " Hello World! "; // test substring System.out.println( "\nSubstring from index 5 to end is " + "\"" + s.substring( 5 ) + "\""); System.out.println( "s after trim = \"" + s.trim() + "\""); System.out.println( "s = \"" + s + "\""); } } >java S2 Substring from index 5 to end is "llo World! " s after trim = "Hello World!" s = " Hello World! "

  23. Example • Write a program that asks for user's name (always consists of two names) and then writes it back with the first name as entered, and the second name in capital letters.

  24. MichaelJackson spaceLoc import javax.swing.*; class CapName { public static void main (String args[]) { String inName; String outName; int spaceLoc; inName = JOptionPane.showInputDialog("Enter your name:"); // find space spaceLoc = inName.indexOf(' '); // get first name and last name outName = inName.substring(0, spaceLoc) + " " + inName.substring(spaceLoc+1).toUpperCase(); JOptionPane.showMessageDialog(null, "Welcome, " + outName); System.exit(0); } }

  25. Command Line Arguments • public static void main(String args[]) • When runs an application, you can supply a list of arguments - command line argument • The arguments are passed as an array of String (args in the above example) to the main method. What does this parameter mean?

  26. Example 1 import java.util.*; public class CommandLineArgument { public static void main( String args[] ) { for (int i=0; i<args.length; i++) { System.out.println(args[i]); } } } >java CommandLineArgument >java CommandLineArgumentHello Peter Chan Hello Peter Chan >java CommandLineArgument "Hello Peter Chan" "Hello Mary Wong" Hello Peter Chan Hello Mary Wong One string object

  27. Example 2 • Write a program to sum up two command line arguments. import java.util.*; public class AddTwoIntegers { public static void main( String args[] ) { int num1, num2; if (args.length != 2) { System.out.println( "Usage : java AddTwoIntegers <num1> <num2>" ); System.exit(0); } num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } } >java AddTwoIntegers Usage : java AddTwoIntegers <num1> <num2> >java AddTwoIntegers 23 55 The sum is 78

  28. Exercise • Write a program to sum up all command line arguments. >java AddIntegers The sum is 0 >java AddIntegers 22 35 The sum is 57 >java AddIntegers 12 3 5 26 The sum is 44

More Related