Java Data Type Tutorial - Java String Edit








Trimming a String

We can use the trim() method to remove all leading and trailing whitespaces and control characters from a string.

trim() method removes all leading and trailing characters from the string, which have Unicode value less than \u0020 (decimal 32). For example,

Replacing Part of a String

The replace() method takes an old character and a new character as arguments.

It returns a new String object by replacing all occurrences of the old character by the new character. For example,

public class Main {
  public static void main(String[] args) {
    String oldStr = new String("tooth");
    String newStr  = oldStr.replace('o', 'e');
    System.out.println(newStr);
  }
}

The code above generates the following result.