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.
public class SubStringExample {
 public static void main(String[] args) {
  String str = "javaguides";
  
  // substring from start to end
  String subStr = str.substring(0, str.length());
  System.out.println("substring from 0 to length of the string : " + subStr);
  
  subStr = str.substring(4);
  System.out.println("Sub string starts from index 4 : " + subStr);
  
  // Remember index starts from 0
  System.out.println(str.substring(1));
  
  System.out.println("unhappy".substring(2));
  System.out.println("Harbison".substring(3));
  System.out.println("emptiness".substring(8));
 }
}
Output:
substring from 0 to length of the string : javaguides
Sub string starts from index 4 : guides
avaguides
happy
bison
s

concat(String str)

We can concatenate two strings using concat( ). The concat() method concatenates the specified string to the end of this string.
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 +.
Example:
public class ConcatExmaple {
 public static void main(String[] args) {
  String str = "javaguides";
  str = str.concat(".net");
  System.out.println("Concatenates the specified string to the end of this string : " + str);
  
  System.out.println("cares".concat("s"));
  System.out.println("to".concat("get"));
 }
}
Output:
Concatenates the specified string to the end of this string : javaguides.net
caress
toget

replace( ) methods

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)
Example: This is complete example to demonstrate the usage of replace() methods.
public class ReplaceExample {
 public static void main(String[] args) {
  String str = "javaguides";
  String subStr = str.replace('a', 'b');
  System.out.println("replace char 'a' with char 'b' from given string : " + subStr);
  
  subStr = str.replace("guides", "tutorials");
  System.out.println("replace guides with tutorials from given string : " + subStr);
  
  subStr = str.replaceAll("[a-z]", "java");
  System.out.println(subStr);
  
  subStr = str.replaceFirst("[a-z]", "java");
  System.out.println(subStr);
 }
}
Output:
replace char 'a' with char 'b' from given string : jbvbguides
replace guides with tutorials from given string : javatutorials
javajavajavajavajavajavajavajavajavajava
javaavaguides

replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.
Example: This is complete example to demonstrate the usage of replaceAll() methods.
public class ReplaceExample {
 public static void main(String[] args) {
  String str = "javaguides";
  String subStr = str.replaceAll("[a-z]", "java");
  System.out.println(subStr);
 }
} 
Output:
javajavajavajavajavajavajavajavajavajava

replaceFirst(String regex, String replacement)

Replaces the first substring of this string that matches the given regular expression with the given replacement.
Example: This is complete example to demonstrate the usage of replaceFirst() methods.
public class ReplaceExample {
 public static void main(String[] args) {
  String str = "javaguides";
  String subStr = str.replaceFirst("[a-z]", "java");
  System.out.println(subStr);
 }
} 
Output:
javaavaguides

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"));
 }
}
Example 2: This is complete example to demonstrate the usage of trim() method.
public class TrimExample {
 public static void main(String[] args) {
  String str = "javaguides ";
  String subStr = str.trim();
  System.out.println("trim the space from given string : " + subStr);
 }
}
Output:
trim the space from given string : javaguides

GitHub Repository



Reference

Comments