String Variables - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

String Variables

Description:

To append one string after another (concatenation): String joinedString = string1 string2; ... append( aValue ) Appends a string representation of aValue to ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 15
Provided by: alanwi8
Category:

less

Transcript and Presenter's Notes

Title: String Variables


1
String Variables
  • String variables have always presented a
    challenge for programming languages.
  • They have varying sizes, and for internal storage
    purposes, the computer would prefer to predict in
    advance the amount of storage needed for the
    value of a variable.
  • As a result, strings are often a special case
    in a programming language.

2
Strings in Java
  • Strings in Java are also a reference type.
  • They are similar to an array of characters in
    that they represent an ordered sequence of
    characters with positions numbered from 0.
  • String constants are enclosed in double quotes.
  • Example
  • String message "Hello World!"
  • System.out.println( message )
  • The class String provides many useful methods.
  • See page 287 of the text for a longer list of
    useful methods.
  • The complete list is at http//java.sun.com/j2se/1
    .4.2/docs/api/

3
Comparison with character arrays
  • Although a String has many similarities to an
    array of characters, there are some important
    differences.
  • You dont need to use new to create a string
    unless you want to use one of the String class
    constructors
  • String s1 "Hello!"
  • String s2 new String("Hello!")
  • You DO NOT use to access the characters in the
    string.
  • The contents of a String cannot be changed after
    it has been created.
  • You can have a String variable refer to a
    different string, but you cannot change
    characters within the original string.
  • There is NO equivalent to
  • char x new char 'h','e','l','l','o'
  • x2 'q'

4
Conversion to/from character arrays
  • To convert from a character array to a String
  • char x new char 'h','e','l','l','o'
  • String s1 new String( x )
  • To convert from a String to a character array
  • char x aString.toCharArray( )

5
Useful String methods
  • Suppose we have
  • String message "Hello World!"
  • To find the length of a string
  • int theStringLength message.length()
  • To find the character at position i (numbered
    from 0)
  • int i 4
  • char theChar message.charAt( i )

6
Useful String methods
  • To change any primitive data type to a String
  • int anInteger 17
  • String aString String.valueOf( anInteger )
  • To append one string after another
    (concatenation)
  • String joinedString string1 string2

7
Useful String methods
  • To find a particular character or String within a
    String
  • First occurrence of 'x'
  • int location aString.indexOf('x')
  • First occurrence of "world" starting from
    position pos
  • int location2 aString.indexOf( "world", pos )
  • There is also a corresponding method lastIndexOf(
    ) occurrence of "world" starting from position
    pos

8
Useful String methods
  • Substrings
  • The substring method returns a String consisting
    of the characters starting from the first
    position inclusive up to but NOT including the
    second position
  • String str "abcdefghijklmno"
  • String str2 str.substring( 2, 5 )
  • Result is "cde
  • Case changes toLowerCase( ), toUpperCase( )

9
Comparing Strings
  • A String is a reference type and so they are NOT
    compared with .
  • The String class has a method compareTo() to
    compare 2 strings.
  • The characters in each string are compared one at
    a time from left to right, using the collating
    sequence.
  • The comparison stops after a character comparison
    results in a mismatch, or one string ends before
    the other.
  • If str1 lt str2, then compareTo() returns an int lt
    0
  • If str1 gt str2, then compareTo() returns an int gt
    0
  • If the character at every index matches, and the
    strings are the same length, the method returns 0

10
Comparing Strings
  • What is the value of result for these examples?
  • Example 1
  • String str1 "abcde"
  • String str2 "abcfg"
  • int result str1.compareTo(str2)
  • Example 2
  • String str1 "abcde"
  • String str2 "ab"
  • int result str1.compareTo(str2)

11
The class StringBuffer
  • This class is used for modifiable strings.
  • The main use is for collecting large amounts of
    text that is built from smaller strings.
  • Methods
  • append( aValue )
  • Appends a string representation of aValue to the
    end of the buffer.
  • aValue could be a string or a value of any
    primitive type int, double, boolean, etc.
  • insert( position, aValue )
  • Inserts a string at a specific position in the
    buffer.

12
The class StringTokenizer
  • This class is useful for separating a large
    string into smaller parts.
  • Tokens are the desired parts of the string
  • For example words.
  • The class uses delimiters to identify the
    points at which a string must be split into
    tokens.
  • By default, the delimiters are the set of white
    space characters blank, tab, new-line.
  • You can supply your own list of characters as the
    set of delimiters.
  • You can also choose whether a delimiter is
    returned or not as a token.
  • Normally, they are not returned as tokens

13
StringTokenizer methods
  • The string tokenizer is set up to return one
    token at a time, as long as there are tokens
    remaining.
  • Each time a token is returned, the tokenizer
    internally moves to the next token.
  • Create a tokenizer
  • import java.util.StringTokenizer
  • StringTokenizer st new StringTokenizer( aString
    )
  • Method to count the number of tokens
  • int numberOfTokens st.countTokens( )
  • Method that returns true if there are more tokens
    remaining
  • boolean moreTokens st.hasMoreTokens( )
  • Method to return the next token
  • String aString st.nextToken( )

14
StringTokenizer constructors
  • Create a string tokenizer that does not include
    the delimiters as tokens
  • StringTokenizer st new StringTokenizer( aString
    )
  • Create a string tokenizer than uses each
    character of the second string as a delimiter
  • StringTokenizer st2 new StringTokenizer(
    aString, " .,!\n\t" )
  • Create a string tokenizer that returns the
    delimiters as tokens
  • StringTokenizer st3 new StringTokenizer(
    aString, " \n\t", true )
Write a Comment
User Comments (0)
About PowerShow.com