AppDividend
Latest Code Tutorials

Java Trim String: How To Trim String In Java

The java lang. String.trim() is the inbuilt function that eliminates leading and trailing spaces. 

Java String trim()

Java trim() is a built-in string method used to remove leading and trailing spaces from a given string. For example, the Unicode value of space “”is ‘\u0020’; this method finds this Unicode value before and end of a string. If this value is found, it removes that space and returns the omitting String.

Syntax

public String trim()

Remember, this method does not have any parameters.

Example

See the following example.

public class StringTrim
{
	public static void main(String args[])
	{
		String str="   Welcome to Appdividend   ";
		System.out.println("String without trim() is: \n"+str);
		System.out.println("Also the length of the string is: "+str.length());

		String s=str.trim();
		System.out.println("\nString after triming is: \n"+s);
		System.out.println("After triming length of the string: "+s.length());
	}
}

See the output.

➜  java javac StringTrim.java
➜  java java StringTrim
String without trim() is:
   Welcome to Appdividend
Also the length of the string is: 28

String after triming is:
Welcome to Appdividend
After triming length of the string: 22
➜  java

How to remove the last Character from String in Java

To remove the last Character from a string in Java, use the trim() method.

See the following code.

public class StringTrim {
	public static void main(String args[]) {
		String str = "KRUNAL";
		if (str != null && str.length() > 0) {
			str = str.substring(0, str.length() - 1);
		}
		System.out.println(str);
	}
}

See the output.

➜  java javac StringTrim.java
➜  java java StringTrim
KRUNA
➜  java

You can add null != str && at the beginning of the check. 

You can also use the one-liner function to do that same job.

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

Java string trim whitespace()

  1. We can eliminate the leading and trailing spaces of a string in Java with the help of trim().
  2. The trim() method is defined under the String class of the Java.lang package.
  3. It does not eliminate the middle spaces of the String.
  4. A new String object is returned by calling the trim(,) method.
  5. It doesn’t replace the value of the String object. Therefore if we want access to the new String object, we need to reassign it to the old String or assign it to a new variable.

See the following example.

public class StringTrim {
	public static void main(String args[]) {

		String str2 = "      Millie   Bobby     Brown!!!      ";
		System.out.println(str2);
		System.out.println(str2.trim());
	}
}

See the output.

➜  java java StringTrim
      Millie   Bobby     Brown!!!
Millie   Bobby     Brown!!!
➜  java

Remove only trailing spaces with regular expression

The below example utilizes the regular expression to find all trailing white spaces. Once you have all trailing white spaces, you can replace them with an empty string.

public class StringTrim {
	public static void main(String args[]) {

		String regex = "\\s+$";

		String kb = "appdividend.com   "; // 3 trailing spaces
		String kl = "   appdividend.com   "; // 3 leading and trailing spaces

		String op1 = kb.replaceAll(regex, "");
		String op2 = kl.replaceAll(regex, "");

		System.out.println(op1);
		System.out.println(op2);
	}
}

See the output.

➜  java java StringTrim
appdividend.com
   appdividend.com
➜  java

Remove trailing whitespaces with Character.isWhitespace()

The isWhitespace() method iterate the String characters from the end. It checks if the Character is the white space character and replaces it with an empty character.

This iteration goes on until a non-whitespace character is found.

See the following code.

public class StringTrim {
	public static void main(String args[]) {
		String kb = "appdividend.com   "; // 3 trailing spaces
		String kl = "   appdividend.com   "; // 3 leading and trailing spaces

		System.out.println(removeTrailingSpaces(kb));
		System.out.println(removeTrailingSpaces(kl));
	}

	public static String removeTrailingSpaces(String str) {
		if (str == null)
			return null;
		int len = str.length();
		for (; len > 0; len--) {
			if (!Character.isWhitespace(str.charAt(len - 1)))
				break;
		}
		return str.substring(0, len);
	}
}

See the output.

➜  java java StringTrim
appdividend.com
   appdividend.com
➜  java

Conclusion

We have seen how to remove trailing spaces, remove the last Character from a string, remove spaces using regex.

That’s it for this tutorial.

Recommended Posts

Java String valueOf()

The charAt() In Java

Java String equalsIgnoreCase()

Java String Class

StringBuilder Class in Java

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.