Showing posts with label Modifying a String. Show all posts
Showing posts with label Modifying a String. Show all posts

Sunday, July 8, 2012

StringBuffer in java

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 will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth. Java
uses both classes heavily, but many programmers deal only with String and let Java
manipulate StringBuffers behind the scenes by using the overloaded + operator.



StringBuffer Constructors
 
StringBuffer defines these three constructors:



  1. StringBuffer( )
  2. StringBuffer(int size)
  3. 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. Also, frequent reallocations can fragment memory. By
allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.

Saturday, April 28, 2012

Modifying a String

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.


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. 

The second form of substring( ) allows you to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.
The following program uses substring( ) to replace all instances of one substring with another within a string:


// 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.



concat()
You can concatenate two strings using concat( ), shown here: 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 +. For example,
 String s1 = "one"; String s2 = s1.concat("two");


puts the string “onetwo” into s2. It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two";


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) Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example, String s = "Hello".replace('l', 'w'); puts the string “Hewwo” into s.


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 state’s capital. It uses trim( ) to remove any leading or trailing whitespace that may have inadvertently been entered by the user.


// Using trim() to process commands.

 import java.io.*;
 class UseTrim
  {
   public static void main(Strinargs[])
      throws IOException {

 // create a BufferedReader using System.in

 BufferedReader br = new BufferedReader(new 
 InputStreamReader(System.in));

String str;

System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");

do 


str = br.readLine(); str = str.trim();

// remove whitespace 

if(str.equals("Illinois"))

System.out.println("Capital is 
Springfield.");

else if(str.equals("Missouri"))

System.out.println("Capital is Jefferson 
City.");

 else if(str.equals("California")) 
  System.out.println("Capital is Sacramento."); 
else if(str.equals("Washington")) 

System.out.println("Capital is Olympia.");

//
... } while(!str.equals("stop")); 
}
 }