Java String trim() method

The java lang.string.trim()is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is ‘\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

Signature

The signature or syntax of string trim method is given below:

public String trim()
Returns

It returns the omitted string with no leading and trailing spaces.

Java String trim() method example

To show the working of string trim() function.

// Java program to demonstrate working // of java string trim() method class Test { // driver code public static void main(String args[]) { // trims the trailing and leading spaces String s = " cprogramcoding for cprogramcoding has all java functions to read "; System.out.println(s.trim()); // trims the leading spaces s = " Rama loves reading books"; System.out.println(s.trim()); } }


Output:
cprogramcoding for cprogramcoding has all java functions to read Rama loves reading books
Java String trim() method example
public class Test { public static void main(String args[]) { String str1=" hello cprogramcoding "; System.out.println(str1+"For free tutorail"); System.out.println(str1.trim()+"For free tutorail"); } }


Output:
hello cprogramcoding For free tutorail hello cprogramcodingFor free tutorail
Java String trim() method example
public class Test { public static void main(String[] args) { String str1 =" hello cprogramcoding string "; System.out.println(str1.length()); System.out.println(str1); String tr1 = str1.trim(); System.out.println(tr1.length()); System.out.println(tr1); } }


Output:
32 hello cprogramcoding string 27 hello cprogramcoding string



Instagram