String Modifying Methods with Examples

String Modifying Methods Overview

As we know that 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 in this post.

In this post, we will discuss below methods for modifying a String objects.

substring()

concat()

replace()

replaceAll()

replaceFirst()

trim()

String Modifying Methods with Examples

substring() methods

We can extract a substring using substring( ) methods. There are two forms of substring() methods.

substring(int beginIndex) - Returns a string that is a substring of this string.

substring(int beginIndex, int endIndex) - Returns a string that is a substring of this string.

These methods throws IndexOutOfBoundsException- if beginIndex is negative or larger than the length of this String object.

Example: This is complete example to demonstrate the usage of both substring() methods.

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.