Java remove trailing whitespaces from String

Java program to remove trailing whitespaces from a String. This example will help you to trim only trailing whitespaces from a String in Java.

1. Java program to remove only trailing spaces with regular expression

This example utilizes regular expression to find all trailing white spaces. Once you have all trailing while spaces, you can replace them with empty string.

String regex = "\\s+$";
		
String originalString1 = "howtodoinjava.com   ";	//3 trailing spaces
String originalString2 = "   howtodoinjava.com   ";	//3 leading and trailing spaces

String trimmedString1 = originalString1.replaceAll(regex, "");
String trimmedString2 = originalString2.replaceAll(regex, "");

System.out.println(trimmedString1);
System.out.println(trimmedString2);

Program output.

howtodoinjava.com
   howtodoinjava.com

2. Java remove trailing whitespaces with Character.isWhitespace() method

This method iterate the characters of string from end. It checks if character is white space character then it replaces it with empty character.

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

public class StringExample 
{
	public static void main(String[] args) 
	{
		String originalString1 = "howtodoinjava.com   "; // 3 trailing spaces
		String originalString2 = "   howtodoinjava.com   "; // 3 leading and trailing spaces

		System.out.println(removeTrailingSpaces(originalString1));
		System.out.println(removeTrailingSpaces(originalString2));
	}

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

Program output.

howtodoinjava.com
   howtodoinjava.com

3. Java program to remove leading and trailing spaces

If you want to remove all leading and trailing spaces from string, then best way is to use String.trim() method.

String originalString1 = "howtodoinjava.com   "; // 3 trailing spaces
String originalString2 = "   howtodoinjava.com   "; // 3 leading and trailing spaces

String trimmedString1 = originalString1.trim();
String trimmedString2 = originalString2.trim();

System.out.println(trimmedString1);
System.out.println(trimmedString2);

Program output.

howtodoinjava.com
howtodoinjava.com

Use above given examples to trim trailing spaces from String in Java.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.