Copyrights © 2012 Jatin Kotadiya. All Rights Reserved . Powered by Blogger.

Wednesday, October 31, 2012

String Handling


                                 13:  String Handling
Overview
Ø  As is the case in most other programming languages, in Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String.
Ø  Implementing strings as built-in objects allows Java to provide a full complement of features that make string handling convenient.
Ø  Somewhat unexpectedly, when you create a String object, you are creating a string that cannot be changed.
Ø  That is, once a String object has been created, you cannot change the characters that comprise that string. At first, this may seem to be a serious restriction.
Ø  The difference is that each time you need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged.
Ø  This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones.
Ø  For those cases in which a modifiable string is desired, there is a companion class to String called StringBuffer, whose objects contain strings that can be modified after they are created.
Ø  Both the String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically.
Ø  This allows certain optimizations that increase performance to take place on common string operations.
Ø  One last point: To say that the strings within objects of type String are unchangeable means that the contents of the String instance cannot be changed after it has been created. However, a variable declared as a String reference can be changed to point at some other String object at any time.

1.   The String Constructors  
The String class supports several constructors. To create an empty String, you call the default constructor.
For example,
  String s = new String();    
 will create an instance of String with no characters in it.
Class StringDemo
{
          Public static void main(String args[])
          {
                   String s1=new String(“BCA Dept.”);
                   String s2;
                   S2=s1+”,Saurashtra University”;
                   Syste.out.println(s2);
          }
}
Output : BCA Dept.,Saurashtra University
Ø  The String class provides a variety of constructors to handle this.
Ø  To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ])    
 Here is an example:    
char chars[] = { 'b', 'c', 'a' };
String s = new String(chars);
 This constructor initializes s with the string "abc".

Ø  You can specify a subrange of a character array as an initializer using the following constructor:
 String(char chars[ ], int startIndex, int numChars)    
 Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example:
 char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
 This initializes s with the characters cde.

Ø  You can construct a String object that contains the same character sequence as another String object using this constructor:
  String(String strObj)    
 Here, strObj is a String object. Consider this example:    
 // Construct one String from another.
class MakeString {
  public static void main(String args[]) {
    char c[] = {'J', 'a', 'v', 'a'};
    String s1 = new String(c);
    String s2 = new String(s1); 

    System.out.println(s1);
    System.out.println(s2);
  }
}
 The output from this program is as follows:    
 Java
Java
Ø  As you can see, s1 and s2 contain the same string.    
Ø  Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common.

Ø  The String class provides constructors that initialize a string when given a byte array. Their forms are shown here:

String(byte asciiChars[ ])
String(byte asciiChars[ ],  int startIndex, int numChars)

Ø  Here, asciiChars specifies the array of bytes. The second form allows you to specify a subrange. In each of these constructors, the byte-to-character conversion is done by  using the default character encoding of the platform.

Ø  The following program illustrates these constructors:
// Construct string from subset of char array.
class SubStringCons {
  public static void main(String args[]) {
    byte ascii[] = {65, 66, 67, 68, 69, 70 };

    String s1 = new String(ascii);
    System.out.println(s1);

    String s2 = new String(ascii, 2, 3);
    System.out.println(s2);

2.   String Length

Ø  The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here:

 int length( )    

 The following fragment prints "3", since there are three characters in the string s:    


char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());

3.   Special String Operations

Ø  These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation.
 
 String Literals  
Ø  For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object.
Ø  For example, the following code fragment creates two equivalent strings:  

char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);

String s2 = "abc"; // use string literal

Ø  Because a String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows.

Ø  It calls the length( ) method on the string "abc". As expected, it prints "3".
 
  System.out.println("abc".length());

String Concatenation  

Ø  This allows you to chain together a series of + operations.
Ø  For example, the following fragment concatenates three strings:
 String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);

This displays the string "He is 9 years old."    

Ø  One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them.
Ø  Here is an example:

 // Using concatenation to prevent long lines.
class ConCat
{
  public static void main(String args[])
 {
    String longStr = "This could have been " + "a very long line that would have " + "wrapped around.  But string concatenation " + "prevents this.";

    System.out.println(longStr);
  }
}

String Concatenation with Other Data Types  
Ø  You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example:
 int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);

Ø  In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before.
Ø  Be careful when you mix other types of operations with string concatenation expressions, However. You might get surprising results. Consider the following:  
 String s = "four: " + 2 + 2;
System.out.println(s);
 Output -  four: 22    
 rather than the    
 four: 4    
 String s = "four: " + (2 + 2);    
 Now s contains the string "four: 4".
String Conversion and toString( )
The toString( ) method has this general form:
 String toString( )    
Ø  To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.
Ø  For example, they can be used in print( ) and println( ) statements and in concatenation expressions. The following program demonstrates this by overriding toString( ) for the Box class:
 // Override toString() for Box class.
class Box {
  double width;
  double height;
  double depth;
 Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
 }
 public String toString() {
    return "Dimensions are " + width + " by " + 
            depth + " by " + height + ".";
  }
}
class toStringDemo
 {
  public static void main(String args[])
 {
    Box b = new Box(10, 12, 14);
    String s = "Box b: " + b; // concatenate Box object

    System.out.println(b); // convert Box to string
    System.out.println(s);
  }
}  
 The output of this program is shown here:    
Dimensions are 10 by 14 by 12.
Box b: Dimensions are 10 by 14 by 12
4.   Character Extraction
Method
Description
Char charAt(int indexnum)
Extract a single character and index no. provides the no. of char you want to extract.
Void  getChars(int sourceStart, int sourceEnd, char target[], char targetStart)
SourceStart specifies the index of the beginning of the substring, and sourceEnd specifies an index that is one past the end of the desired substring. Thus, the substring contains the characters from sourceStart through sourceEnd–1.
The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart.
Byte[] getBytes()
There is an alternative to getChars( ) that stores the characters in an array of bytes.
It uses the default character-to-byte conversions
provided by the platform.
Char[] toCharArray()
If you want to convert all the characters in a String object into a character array.
 It returns an array of characters for the entire string.

5.   String Comparison

1.    equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
Ø  To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)
Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):    
 // Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
  public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = "Hello";
    String s3 = "Good-bye";
    String s4 = "HELLO";
    System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
    System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
    System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
    System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
  }
}
 The output from the program is shown here:    
 Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

2.   regionMatches( )

The regionMatches( ) method compares a specific region inside a string with another specific region in another string. There is an overloaded form that allows you to ignore
case in such comparisons. Here are the general forms for these two methods:

boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)

 boolean regionMatches(boolean ignoreCase, int startIndex, String str2,                                  int str2StartIndex, int numChars)



3.   startsWith( ) and endsWith( )  

Ø  String defines two routines that are, specialized forms of regionMatches().
Ø  The startsWith( ) method determines whether a given String begins with a specified string. The endsWith( ) determines whether the String in question ends with a specified string.
Ø  They have the following general forms:
 
boolean startsWith(String str)
boolean endsWith(String str)

Ø  Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is returned. For example,

 "Foobar".endsWith("bar")    

  and    

  "Foobar".startsWith("Foo")     are both true.    

Ø  A second form of startsWith( ), shown here, lets you specify a starting point:    

  boolean startsWith(String str, int startIndex)    
 
Ø  Here, startIndex specifies the index into the invoking string at which point the search will begin. For example,
 
  "Foobar".startsWith("bar", 3)     returns true.

4.   equals( ) Versus ==
Ø  It is important to understand that the equals( ) method and the == operator perform two different operations.

Ø  As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

Ø  The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

class EqualsNotEqualTo {
  public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = new String(s1);
    System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
    System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
  }
}
Ø  The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer.
Ø  Thus, the contents of the two String objects are identical, but they are distinct objects. This means that s1 and s2 do not refer to the same objects and are, therefore, not ==, as is shown here by the output of the preceding example:  

Hello equals Hello -> true
Hello == Hello -> false

5.   Searching Strings

Ø  The String class provides two methods that allow you to search a string for a specified character or substring:

       indexOf( ) Searches for the first occurrence of a character or substring.    

       lastIndexOf( ) Searches for the last occurrence of a character or substring.    

Ø  These two methods are overloaded in several different ways. In all cases, the methods return the index at which the character or substring was found, or –1 on failure.

Ø  To search for the first occurrence of a character, use     

  int indexOf(int ch) To search for the last occurrence of a character, use    

  int lastIndexOf(int ch) Here, ch is the character being sought.    

Ø  To search for the first or last occurrence of a substring, use    
  int indexOf(String str)
  int lastIndexOf(String str)

   Here, str specifies the substring.    

Ø  You can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)

int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

 Here, startIndex specifies the index at which point the search begins. For indexOf( ), the
search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs
from startIndex to zero.




// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
  public static void main(String args[]) {
    String s = "Now is the time for all good men " +
               "to come to the aid of their country.";

    System.out.println(s);
    System.out.println("indexOf(t) = " +s.indexOf('t'));
    System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t'));
    System.out.println("indexOf(the) = " + s.indexOf("the"));
    System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
    System.out.println("indexOf(t, 10) = " +  s.indexOf('t', 10));
    System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
    System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
    System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
  }
}
Here is the output of this program:    

Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
               lastIndexOf(the, 60) = 55


6.   Modifying a String

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.

1.   substring( )

You can extract a substring using substring( ). It has two forms. The first is    

  String substring(int startIndex)    

Here, startIndex specifies the index at which the substring will begin. This form returns a
copy of the substring that begins at startIndex and runs to the end of the invoking string.

String substring(int startIndex, int endIndex)


/ Substring replacement.
class StringReplace {
  public static void main(String args[]) {
    String org = "This is a test. This is, too.";
    String search = "is";
    String sub = "was";

    String result = "";
    int i;

    do { // replace all matching substrings
      System.out.println(org);
      i = org.indexOf(search);
      if(i != -1) {
        result = org.substring(0, i);
        result = result + sub;
        result = result + org.substring(i + search.length());
        org = result;
      }
    } while(i != -1);

  }
}

The output from this program is shown here:    

This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
               Thwas was a test. Thwas was, too.

2.   concat( )

String concat(String str)    

 This method creates a new object that contains the invoking string with the contents of str  appended to the end. concat( ) performs the same function as +.

3.   replace( )

The replace( ) method replaces all occurrences of one character in the invoking string
with another character. It has the following general form:

String replace(char original, char replacement)    

String s = "Hello".replace('l', 'w');    
puts the string "Hewwo" into s.
4.   trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed. It has this general form:

  String trim( )    

  Here is an example:    
   String s = "   Hello World    ".trim();    

  This puts the string "Hello World" into s.    


The trim( ) method is quite useful when you process user commands.
For example, the following program prompts the user for the name of a state and then displays that tate's capital.
It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.

7.   Data Conversion Using valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable form.
It is a static method that is overloaded within String for all of Java's built-in types, so that
each type can be converted properly into a string.
valueOf( ) is also overloaded for type Object, so an object of any class type you create can also be used as an argument.
Here are a few of its forms:

static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])

For most arrays, valueOf( ) returns a rather cryptic string, which indicates that it is an array of some type.
For arrays of char, however, a String object is created that contains the characters in the char array.
There is a special version of valueOf( ) that allows you  to specify a subset of a char array.
It has this general form:

static String valueOf(char chars[ ], int startIndex, int numChars)

8.   Changing the Case of Characters Within a String

The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase.
The toUpperCase( ) method converts all the characters in a string from  lowercase to uppercase.
Nonalphabetical characters, such as digits, are unaffected.
Here are the general forms of these methods:

String toLowerCase( )
String toUpperCase( )

// Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {
  public static void main(String args[]) 
  {
    String s = "This is a test.";

    System.out.println("Original: " + s);

    String upper = s.toUpperCase();
    String lower = s.toLowerCase();

    System.out.println("Uppercase: " + upper);
    System.out.println("Lowercase: " + lower);
  }
}

 The output produced by the program is shown here:    

Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.





9.   StringBuffer

Ø  StringBuffer is a peer class of String that provides much of the functionality of strings.
Ø  As you know, String represents fixed-length, immutable character sequences.
Ø  In contrast, StringBuffer represents growable and writeable character sequences.
Ø  StringBuffer may have characters and substrings inserted in the middle or appended to the end.

StringBuffer Constructors

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)

Ø  The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.
Ø  The second version accepts an integer argument that explicitly sets the size of the buffer.
Ø  The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
Ø  StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time.

length( ) and capacity( )

Ø  The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method.

Ø   int length( )   &   int capacity( )

// StringBuffer length vs. capacity.
class StringBufferDemo {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("Hello");
     System.out.println("buffer = " + sb);
    System.out.println("length = " + sb.length());
    System.out.println("capacity = " + sb.capacity());
  }
}

buffer = Hello
length = 5
capacity = 21

Ø  Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.

ensureCapacity( )

Ø  If you want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer.

void ensureCapacity(int capacity)    
Ø  Here, capacity specifies the size of the buffer.

setLength( )

Ø  To set the length of the buffer within a StringBuffer object, use setLength( ).

void setLength(int len)
Ø  Here, len specifies the length of the buffer. This value must be nonnegative.

charAt( ) and setCharAt( )

Ø  The value of a single character can be obtained from a StringBuffer via the charAt( ) method.
Ø  You can set the value of a character within a StringBuffer using setCharAt( ).

char charAt(int where)
void setCharAt(int where, char ch)

// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("Hello");
    System.out.println("buffer before = " + sb);
    System.out.println("charAt(1) before = " + sb.charAt(1));
      sb.setCharAt(1, 'i');
      sb.setLength(2);
      System.out.println("buffer after = " + sb);
      System.out.println("charAt(1) after = " + sb.charAt(1));
  }
}

 Here is the output generated by this program:    
 buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i

getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:
 void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
append( )

Ø  The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object.

StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

// Demonstrate append().
class appendDemo {
  public static void main(String args[]) {
    String s;
    int a = 42;
    StringBuffer sb = new StringBuffer(40);

    s = sb.append("a = ").append(a).append("!").toString();
    System.out.println(s);
  }
}
 The output of this example is shown here:    

  a = 42!

Ø  The append( ) method is most often called when the + operator is used on String objects. Java automatically changes modifications to a String instance into similar operations on a StringBuffer instance.
Ø  Thus, a concatenation invokes append( ) on a StringBuffer object. After the concatenation has been performed, the compiler inserts a call to toString( ) to turn the modifiable StringBuffer back into a constant String.
Ø  All of this may seem unreasonably complicated. Why not just have one string class and have it behave more or less like StringBuffer?
Ø  The answer is performance. There are many optimizations that the Java run time can make knowing that String objects are immutable.
Ø  Thankfully, Java hides most of the complexity of conversion between Strings and StringBuffers.

insert( )

Ø  The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects.
Ø  Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with.
Ø  This string is then inserted into the invoking StringBuffer object. These are a few of its forms:

StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Ø  Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object.

// Demonstrate insert().
class insertDemo {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("I Java!");
     sb.insert(2, "like ");
    System.out.println(sb);
   }
}
 The output of this example is shown here:    
 I like Java!

reverse( )

StringBuffer reverse( )    

Ø  This method returns the reversed object on which it was called.

class ReverseDemo {
  public static void main(String args[]) {
    StringBuffer s = new StringBuffer("abcdef");

    System.out.println(s);
    s.reverse();
    System.out.println(s);
  }
}
 Here is the output produced by the program:    
 Abcdef
Fedcba

delete( ) and deleteCharAt( )

StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)

Ø  The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex specifies an index one past the last character to remove. Thus, the substring deleted runs from startIndex to endIndex–1.

Ø  The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("This is a test.");

    sb.delete(4, 7);
    System.out.println("After delete: " + sb);

    sb.deleteCharAt(0);
    System.out.println("After deleteCharAt: " + sb);
  }
}
 The following output is produced.
After delete: This a test.
After deleteCharAt: his a test


replace( )  

Another new method added to StringBuffer by Java 2 is replace( ). It replaces one set of characters with another set inside a StringBuffer object. Its signature is shown here:

 StringBuffer replace(int startIndex, int endIndex, String str)    
 
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

 // Demonstrate replace()
class replaceDemo {
  public static void main(String args[]) {
    StringBuffer sb = new StringBuffer("This is a test.");

    sb.replace(5, 7, "was");
    System.out.println("After replace: " + sb);
  }
}
 Here is the output:    

 After replace: This was a test.

0 comments:

Post a Comment