1 / 36

Strings

Strings. Chapter 6. Goals and Objectives. Write code using the String class. Manipulate and compare strings using the String class and its methods. Learn about literal strings Learn about String constructors and commonly used methods

dacia
Download Presentation

Strings

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. Strings Chapter 6

  2. Goals and Objectives • Write code using the String class. • Manipulate and compare strings using the String class and its methods. • Learn about literal strings • Learn about String constructors and commonly used methods • Develop code with correct and efficient use of repetitive control structures. • Apply problem solving strategies. • Understand immutability of strings • Learn to format numbers into strings and extract numbers from strings • Learn several useful methods of the Character class • Learn about the StringBuffer class

  3. The String Class • Part of the java.lang package • A String object is comprised of a sequence of characters with the first character at index position 0

  4. The String class • An object of the String class represents a string of characters. • Like other classes, String has constructors and methods. • Unlike other classes, String has two operators, + and += (used for concatenation).

  5. Literal Strings • Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. • Literal strings don’t have to be constructed: they are “just there.”

  6. Literal Strings (cont’d) • The string text may include “escape” characters (\) For example: • \\ stands for \ • \n stands for the newline character • \t – tab • \” – double quotes • \’ – single quote String s1 = "Biology”; String s2 = "C:\\jdk1.4\\docs"; String s3 = "Hello\n";

  7. heLlO hello String Assignment Strings are immutable. Assigning a new string to a String object simply changes the object reference to point to the new string in memory: String text; text = "heLlO"; text = text.toLowerCase(); text

  8. Empty Strings • An empty string has no characters; its length is 0. • Not to be confused with an uninitialized string: Empty strings String s1 = ""; String s2 = new String(); errorMsg is null private String errorMsg;

  9. Null String • String name; // null string • Does not have a length.

  10. Declaring a String • String name = “Bob”; 012 OR String name = new String(“Bob’); 012

  11. new Operator • String s1 = “Bob”; • String s2 = s1; • String s1 = “Bob”; • String s2 = new String(“Bob”); S1 Bob S2 Bob s1 Bob s2

  12. Constructors • String’s no-args and copy constructors are not used much. • Other constructors convert arrays into strings String s1 = new String (); String s2 = new String (s1); String s1 = ""; String s2 = s1;

  13. Immutability • Once created, a string cannot be changed: none of its methods changes the string. • Such objects are called immutable. • Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.

  14. "Sun" "Sun" "Sun" Immutability (cont’d) • Advantage: more efficient, no need to copy. String s1 = "Sun"; String s2 = s1; String s1 = "Sun"; String s2 = new String(s1); s1 s1 s2 s2 Less efficient: wastes memory OK

  15. "sun" "Sun" Immutability (cont’d) • Disadvantage: less efficient — you need to create a new string and throw away the old one for every small change. String s = "sun"; char ch = Character.toUpperCase(s.charAt (0)); s = ch + s.substring (1); s

  16. Comparing Strings The String class includes several methods for comparing two strings:equals()equalsIgnoreCase()compareTo()compareToIgnoreCase()indexOf()lastIndexOf()

  17. int length (); char charAt (k); Returns the number of characters in the string Returns the k-th char Methods — length, charAt Character positions in strings are numbered starting from 0 Returns: ”Flower".length(); ”Wind".charAt (2); 6 ’n'

  18. Methods — substring String s2 = s.substring (i, k); returns the substring of chars in positions from i to k-1 String s2 = s.substring(i); returns the substring from the i-th char to the end strawberry i k strawberry i Returns: "raw" "happy" "" (empty string) ”strawberry".substring (2,5); "unhappy".substring (2); "emptiness".substring (9);

  19. Methods — Concatenation String result = s1 + s2; concatenates s1 and s2 String result = s1.concat (s2); the same as s1 + s2 result+= s3; concatenates s3 to result result += num; converts num to String and concatenates it to result

  20. Methods — Find (indexOf) 0 8 11 15 String date ="July 5, 2012 1:28:19 PM"; date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 date.indexOf ("2020"); -1 date.lastIndexOf ('2'); 15 Returns: (starts searching at position 9) (not found)

  21. Methods — Comparisons boolean b = s1.equals(s2); returns true if the string s1 is equal to s2 boolean b = s1.equalsIgnoreCase(s2); returns true if the string s1 matches s2, case-blind int diff = s1.compareTo(s2); returns the “difference” s1-s2 int diff = s1.compareToIgnoreCase(s2); returns the “difference” s1 - s2, case-blind

  22. Methods — Replacements String s2 = s1.trim (); returns a new string formed from s1 by removing white space at both ends String s2 = s1.replace(oldCh, newCh); returns a new string formed from s1 by replacing all occurrences of oldCh with newCh String s2 = s1.toUpperCase(); String s2 = s1.toLowerCase(); returns a new string formed from s1 by converting its characters to upper (lower) case

  23. Replacements (cont’d) • Example: how to convert s1 to upper case • A common bug: s1 = s1.toUpperCase(); s1 remains unchanged s1.toUpperCase();

  24. Numbers to Strings • Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods.

  25. Numbers to Strings (cont’d) • The DecimalFormat class can be used for formatting numbers into strings. import java.text.DecimalFormat; ... DecimalFormat money = new DecimalFormat("0.00"); ... double amt = 56.7381; ... String s = money.format (amt); 56.7381 "56.74"

  26. Numbers to Strings (cont’d) • Java 5.0 added printf and format methods: int m = 5, d = 19, y = 2007; double amt = 123.5; System.out.printf ( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); String s = String. format( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); Displays, sets s to: "Date: 05/19/2007 Amount 123.50"

  27. Numbers from Strings String s1 = "-123", s2 = "123.45"; int n = Integer.parseInt(s1); double x = Double.parseDouble(s2); • These methods throw a NumberFormatException if s does not represent a valid number (integer, real number, respectively).

  28. Numbers from Strings (cont’d) • A safer way: int n; do { try { n = Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println("Invalid input, reenter"); } } while (...);

  29. Character Methods • java.lang.Character is a “wrapper” class that represents characters as objects. • Character has several useful static methods that determine the type of a character (letter, digit, etc.). • Character also has methods that convert a letter to the upper or lower case.

  30. Character Methods (cont’d) if (Character.isDigit (ch)) ... .isLetter... .isLetterOrDigit... .isUpperCase... .isLowerCase... .isWhitespace... return true if ch belongs to the corresponding category Whitespace is space, tab, newline, etc.

  31. Character methods (cont’d) char ch2 = Character.toUpperCase (ch1); .toLowerCase (ch1); if ch1 is a letter, returns its upper (lower) case; otherwise returns ch1 int d = Character.digit (ch, radix); returns the int value of the digit ch in the given int radix char ch = Character.forDigit (d, radix); returns a char that represents int d in a given int radix

  32. The StringBuffer Class • Represents a string of characters as a mutable object • Constructors: StringBuffer() // empty StringBuffer of the default capacity StringBuffer(n) // empty StringBuffer of a given capacity StringBuffer(str) // converts str into a StringBuffer • Adds setCharAt, insert, append, and delete methods • The toString method converts this StringBuffer into a String

  33. Review: • What makes the String class unusual? • How can you include a double quote character into a literal string? • Is "length".length() allowed syntax? If so, what is the returned value? • Define immutable objects. • Does immutability of Strings make Java more efficient or less efficient?

  34. Review (cont’d): • How do you declare an empty string? • Why are String constructors not used very often? • If the value of String city is "Boston", what is returned by city.charAt (2)? By city.substring(2, 4)? • How come String doesn’t have a setCharAt method? • Is s1 += s2 the same as s1 = s1 + s2 for strings?

  35. Review (cont’d): • What do the indexOf methods do? Name a few overloaded versions. • What is more efficient for strings: == and other relational operators or equals and compareTo methods? • What does the trim method do? • What does s.toUpperCase() do to s? • What does the toString method return for a String object?

  36. Review (cont’d): • Name a simple way to convert a number into a string. • Which class has a method for converting a String into an int? • Name a few Character methods that help identify the category to which a given character belongs. • What is the difference between the String and StringBuffer classes?

More Related