Character Strings - PowerPoint PPT Presentation

About This Presentation
Title:

Character Strings

Description:

Title: No Slide Title Last modified by: Prasad Created Date: 5/24/1995 8:16:34 PM Document presentation format: On-screen Show (4:3) Other titles – PowerPoint PPT presentation

Number of Views:66
Avg rating:3.0/5.0
Slides: 10
Provided by: wrightEdu
Learn more at: http://cecs.wright.edu
Category:

less

Transcript and Presenter's Notes

Title: Character Strings


1
Character Strings
  • class String
  • class StringBuffer
  • (Java 1.4 and before thread-safe)
  • class StringBuilder
  • (Java 5 thread-unsafe)
  • (Cf. array of characters)
  • Based on 2-byte Unicode characters

2
class String vs class StringBuffer/StringBuilder
  • immutable
  • contents of String instance unchangeable
  • cannot insert or append characters
  • fixed length
  • s.length()
  • number of characters in the string
  • mutable
  • contents of StringBuffer instance modifiable
  • growable
  • grows automatically when characters added
  • sb.length()
  • sb.capacity()
  • total allocated capacity

3
String literals and concatenation
  • String s abc
  • System.out.println( s def )
  • stands for string concatenation.
  • Built-in operator overload.
  • Left associativity of
  • (s 3 5) evaluates to abc35.
  • (s (3 5)) evaluates to abc8.
  • (5 3 s) evaluates to 8abc.

4
Left Associativity of
  • is an associative operation on integers.
  • (i (j k) ) ( (i j) k)
  • is an associative operation on strings.
  • (s1 (s2 s3) ) ( (s1 s2) s3)
  • However, when expressions mix both strings and
    integers, in the presence of coercion, the
    operation is not associative.
  • (s (i j) ) ! ( (s i) j)

int-plus
string-concat
5
String conversions
  • class Object supports toString()-method to
    convert a class instance into a printable string
    form classname_at_hashcode
  • toString() can be overridden.
  • public String toString() ...
  • println/print methods in System.out, the
    -expressions, and the -statements invoke
    toString() implicitly, to coerce an instance to a
    string.

6
Assignment
  • String s abc
  • s 235
  • s.equals(abc10) true
  • s.equals(abc235) false
  • (Recall that is left-associative.)
  • Type E1
  • E1 E2
  • E1 (Type) ((E1) (E2))

7
(No Transcript)
8
Comparison
  • abc.equals(abc) is true.
  • abc.equalsIgnoreCase(ABC) is true.
  • abc new String(abc) is false.
  • s s is true.
  • s1.compareTo(s2)
  • negative s1 lexicographically precedes s2
  • zero s1 is equal s2
  • positive s1 lexicographically follows s2

9
Useful Methods
  • String t abca
  • String s new String(t)
  • s.charAt(2) is c.
  • s.indexOf(a) is 0.
  • s.indexOf(bc) is 1.
  • s.indexOf(a,2) is 3.
  • s.lastIndexOf(a) is 3.
  • regionMatches, startsWith, endsWith, etc.
  • Pure ASCII applications can be inefficient
    because Java uses 16-bit Unicode characters.
Write a Comment
User Comments (0)
About PowerShow.com