Chapter: Java The Complete Reference - The Java Library - String Handling

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Modifying a String - Java

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete.

Modifying a String

 

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use a String method that constructs a new copy of the string with your modifications complete. A sampling of these methods are described here.

 

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 has two forms. The first 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.

 

The second form of replace( ) replaces one character sequence with another. It has this general form:

 

String replace(CharSequence original, CharSequence replacement)

 

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(String args[]) 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"));

 

}

 

}


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.