AppDividend
Latest Code Tutorials

Java Trim String Example | How To Trim String In Java

0

Java Trim String Example | How To Trim String In Java is today’s topic. Java trim() method is used to remove leading and trailing spaces from a given string. The Unicode value of space “ “ is ‘\u0020’; what this method does is, it finds this Unicode value before and ending of a string. If this value found, it removes that space and returns the omitting string.

Java String trim()

The java lang.string.trim()is the built-in function that eliminates leading and trailing spaces.

Syntax

public String trim()

Remember, this method does not have any parameters.

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

We can remove the last character from the string using 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 example

  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 java.lang package.
  3. It does not eliminate the middle spaces of the string.
  4. By calling the trim() method, a new String object is returned.
  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 characters of string from the end. It checks if the character is white space character, then it replaces it with an empty character.

This iteration goes on until a non-white space 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. Finally, How To Trim String In Java Tutorial is over.

Recommended Posts

Java String valueOf() Example

The charAt() In Java Example

Java String equalsIgnoreCase()

Java String Class Example

StringBuilder Class in Java Example

Leave A Reply

Your email address will not be published.

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